"""Router Qualys Tags V3 — liste, gap analysis, creation"""
from fastapi import APIRouter, Request, Depends, Form
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from ..dependencies import get_db, get_current_user, get_user_perms, can_view, can_edit
from ..services.qualys_tags_service import (
    list_qualys_tags, analyze_gap, create_static_tag,
    delete_tag, generate_console_steps, load_catalog,
)
from ..config import APP_NAME

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


@router.get("/qualys/tagsv3", response_class=HTMLResponse)
def tags_list_page(request: Request, db=Depends(get_db)):
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login")
    perms = get_user_perms(db, user)
    if not can_view(perms, "qualys"):
        return RedirectResponse(url="/dashboard")

    result = list_qualys_tags(db)
    tags = result.get("tags", [])
    tags.sort(key=lambda t: (t["type"], t["name"]))
    stats = {
        "total": len(tags),
        "dyn": sum(1 for t in tags if t["type"] == "DYN"),
        "stat": sum(1 for t in tags if t["type"] == "STAT"),
    }
    return templates.TemplateResponse("qualys_tagsv3.html", {
        "request": request, "user": user, "app_name": APP_NAME,
        "tags": tags, "stats": stats,
        "error": result.get("msg") if not result.get("ok") else None,
    })


@router.get("/qualys/tagsv3/gap", response_class=HTMLResponse)
def tags_gap_page(request: Request, db=Depends(get_db)):
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login")
    perms = get_user_perms(db, user)
    if not can_view(perms, "qualys"):
        return RedirectResponse(url="/dashboard")

    gap = analyze_gap(db)
    console_steps = generate_console_steps(gap.get("missing_dyn", [])) if gap.get("ok") else []
    can_modify = can_edit(perms, "qualys")
    return templates.TemplateResponse("qualys_tagsv3_gap.html", {
        "request": request, "user": user, "app_name": APP_NAME,
        "gap": gap, "console_steps": console_steps, "can_modify": can_modify,
    })


@router.post("/qualys/tagsv3/create-static")
def tags_create_static(request: Request, db=Depends(get_db),
                        name: str = Form(...), color: str = Form(""),
                        description: str = Form("")):
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login")
    perms = get_user_perms(db, user)
    if not can_edit(perms, "qualys"):
        return RedirectResponse(url="/qualys/tagsv3/gap?msg=denied")
    r = create_static_tag(db, name, color, description)
    msg = "created" if r.get("ok") else f"error_{r.get('msg', 'unknown')[:30]}"
    return RedirectResponse(url=f"/qualys/tagsv3/gap?msg={msg}", status_code=303)


@router.post("/qualys/tagsv3/create-all-static")
def tags_create_all_static(request: Request, db=Depends(get_db)):
    """Cree tous les tags STAT manquants en un coup."""
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login")
    perms = get_user_perms(db, user)
    if not can_edit(perms, "qualys"):
        return RedirectResponse(url="/qualys/tagsv3/gap?msg=denied")

    gap = analyze_gap(db)
    if not gap.get("ok"):
        return RedirectResponse(url="/qualys/tagsv3/gap?msg=qualys_err", status_code=303)

    created = failed = 0
    for t in gap.get("missing_stat", []):
        r = create_static_tag(db, t["name"], t["color"], t.get("description", ""))
        if r.get("ok"):
            created += 1
        else:
            failed += 1
    return RedirectResponse(
        url=f"/qualys/tagsv3/gap?msg=bulk_created_{created}_failed_{failed}",
        status_code=303,
    )


@router.get("/qualys/tagsv3/catalog", response_class=HTMLResponse)
def tags_catalog_page(request: Request, db=Depends(get_db)):
    """Page de reference : nom tag / QQL / couleur pour toute la nomenclature V3."""
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login")
    perms = get_user_perms(db, user)
    if not can_view(perms, "qualys"):
        return RedirectResponse(url="/dashboard")
    catalog = load_catalog() or {}
    return templates.TemplateResponse("qualys_tagsv3_catalog.html", {
        "request": request, "user": user, "app_name": APP_NAME,
        "catalog": catalog,
    })


@router.get("/qualys/tagsv3/catalog.json", response_class=JSONResponse)
def tags_catalog_json(request: Request, db=Depends(get_db)):
    user = get_current_user(request)
    if not user:
        return JSONResponse({"error": "Non autorise"}, status_code=403)
    return load_catalog()
