"""Router Tour de garde SecOps"""
from fastapi import APIRouter, Request, Depends, Query
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy import text
from ..dependencies import get_db, get_current_user
from ..config import APP_NAME

router = APIRouter()
templates = Jinja2Templates(directory="app/templates")


@router.get("/duty", response_class=HTMLResponse)
async def duty_page(request: Request, db=Depends(get_db),
                    year: str = Query("")):
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login")

    from datetime import datetime
    year = int(year) if year and year.isdigit() else datetime.now().year
    current_week = datetime.now().isocalendar()[1]
    current_year = datetime.now().year

    rows = db.execute(text("""
        SELECT * FROM secops_duty
        WHERE year = :y
        ORDER BY week_number
    """), {"y": year}).fetchall()

    years = db.execute(text("""
        SELECT DISTINCT year FROM secops_duty ORDER BY year DESC
    """)).fetchall()

    # Competences (hardcoded pour l'instant, pourra etre en DB plus tard)
    competences = [
        {"nom": "Ayoub",   "s1": True, "commvault": False, "m365": True, "symantec": True},
        {"nom": "Mouaad",  "s1": True, "commvault": False, "m365": True, "symantec": True},
        {"nom": "Khalid",  "s1": True, "commvault": False, "m365": True, "symantec": True},
        {"nom": "Thierno", "s1": True, "commvault": True,  "m365": True, "symantec": True},
        {"nom": "Paul",    "s1": True, "commvault": True,  "m365": True, "symantec": True},
    ]

    # Stats : qui a le plus de gardes
    stats = {}
    for r in rows:
        for field in ["tdg_s1", "tdg_symantec", "tdg_m365", "tdg_dmz"]:
            name = getattr(r, field, None)
            if name:
                stats[name] = stats.get(name, 0) + 1

    return templates.TemplateResponse("duty.html", {
        "request": request, "user": user, "app_name": APP_NAME,
        "rows": rows, "year": year, "years": [y.year for y in years],
        "current_week": current_week, "current_year": current_year,
        "competences": competences, "stats": stats,
    })
