"""
Admin Logs Router
Handles retrieval and display of chat logs and statistics for administrators.
"""
from fastapi import APIRouter, Depends, Query, Request, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from typing import Optional, List, Dict, Any

from deps import current_user
from utils.chat_logger import ChatLogger

router = APIRouter()

@router.get("/logs", name="admin_logs_dashboard", response_class=HTMLResponse)
def logs_dashboard(req: Request, user = Depends(current_user)):
    """
    Render the Admin Logs Dashboard.
    """
    if not user:
        from fastapi.responses import RedirectResponse
        lang = req.session.get("lang", "de")
        return RedirectResponse(f"/{lang}/login", status_code=302)

    if user.get("role") != "admin":
        return HTMLResponse("403 admin only", status_code=403)
        
    return req.app.state.render(req, "pages/admin_logs.html", seo={"title": "Admin Logs", "desc": "Chat History & Stats"})

@router.get("/logs/data", name="admin_logs_data")
def get_logs_data(
    req: Request, 
    limit: int = Query(100, ge=1, le=1000), 
    role: Optional[str] = None,
    user: dict = Depends(current_user)
):
    """
    Get raw log data (JSON).
    """
    if user.get("role") != "admin":
        raise HTTPException(status_code=403, detail="Admin access required")
        
    logger = ChatLogger()
    logs = logger.get_recent_logs(limit=limit)
    
    # Optional filtering
    if role:
        logs = [l for l in logs if l.get('character', {}).get('id') == role]
        
    return {"logs": logs}

@router.get("/logs/stats", name="admin_logs_stats")
def get_logs_stats(req: Request, user: dict = Depends(current_user)):
    """
    Get log statistics (JSON).
    """
    if user.get("role") != "admin":
        raise HTTPException(status_code=403, detail="Admin access required")
        
    logger = ChatLogger()
    return logger.get_stats()
