from __future__ import annotations

from urllib.parse import urlsplit

import requests
from fastapi import (
    APIRouter,
    Body,
    Depends,
    FastAPI,
    HTTPException,
    Query,
    Request,
    Response,
)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse

from keepedu_performance.api.auth import (
    Principal,
    current_principal,
    local_session_allowed,
    optional_session_principal,
    require_read,
    require_write,
    session_principal,
)
from keepedu_performance.api import identity
from keepedu_performance.api import grade_entry, jobs, notes, olympics, updates
from keepedu_performance.api.academic_report import generate_academic_report
from keepedu_performance.api.keepedu import student_details as live_student_details
from keepedu_performance.api.repository import (
    Tenant,
    find_student,
    list_filters,
    list_rankings,
    list_students,
    ranking_overview,
    series_name_allowed,
    unit_name_allowed,
)
from keepedu_performance.core.config import settings


app = FastAPI(
    title="KeepEdu Performance API",
    version="1.0.0",
    docs_url="/docs" if settings.api_docs_enabled else None,
    redoc_url=None,
)

# A credencial vai em Authorization: Bearer (nenhum cookie), entao o CORS nao usa credenciais.
cors_origins = [origin for origin in settings.cors_allow_origins if origin != "*"]
if cors_origins:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=cors_origins,
        allow_credentials=False,
        allow_methods=["GET", "POST", "OPTIONS"],
        allow_headers=["Authorization", "Content-Type"],
    )

router = APIRouter(prefix="/api/v1")


def frontend_redirect(request: Request, path: str) -> RedirectResponse:
    """Keep the old platform entry URL working after the frontend/backend split."""
    base = settings.app_public_url.strip().rstrip("/")
    try:
        target = urlsplit(base)
        if (
            target.scheme not in {"http", "https"}
            or not target.hostname
            or target.username
            or target.password
            or target.query
            or target.fragment
            or base == str(request.base_url).rstrip("/")
        ):
            raise ValueError("Invalid frontend URL")
    except ValueError as error:
        raise HTTPException(503, "URL do frontend Performance indisponivel.") from error
    destination = base + path
    if request.url.query:
        destination += "?" + request.url.query
    return RedirectResponse(
        destination,
        status_code=307,
        headers={"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"},
    )


@app.get("/sso", include_in_schema=False)
def legacy_sso_entry(request: Request):
    return frontend_redirect(request, "/sso")


@app.get("/logout", include_in_schema=False)
def legacy_logout_entry(request: Request):
    return frontend_redirect(request, "/logout")


def tenant(principal: Principal) -> Tenant:
    return Tenant(principal.institute_id, principal.academic_year)


@app.get("/health/live", tags=["health"])
def live() -> dict[str, str]:
    return {"status": "ok"}


@app.get("/health/ready", tags=["health"])
def ready() -> dict[str, str]:
    return {"status": "ready"}


@router.post("/auth/login", tags=["auth"])
def auth_login(body: dict[str, str] = Body()):
    if not settings.local_login:
        raise HTTPException(
            403, "Login direto desativado. Entre pelo gestor KeepEdu (SSO)."
        )
    email = body.get("email", "").strip()
    password = (body.get("password") or body.get("senha") or "").strip()
    if not email or not password:
        raise HTTPException(400, "Informe e-mail e senha.")
    try:
        result = identity.login(email, password)
    except PermissionError as error:
        raise HTTPException(401, str(error)) from error
    except Exception as error:
        raise HTTPException(
            502, "Nao foi possivel conectar ao login KeepEdu."
        ) from error
    return {"token": result["token"]}


@router.post("/auth/sso/exchange", tags=["auth"])
def auth_sso_exchange(body: dict[str, str] = Body()):
    token = body.get("token", "").strip()
    if not token:
        raise HTTPException(400, "Token SSO ausente.")
    try:
        result = identity.exchange_sso(token)
    except Exception as error:
        raise HTTPException(
            503, "Nao foi possivel validar o SSO. Tente novamente."
        ) from error
    if result is None:
        raise HTTPException(401, "Token SSO invalido ou expirado.")
    return {"token": result["token"]}


def _gestor_links(principal: Principal) -> dict[str, str]:
    return {
        "school": principal.school,
        "gestorHomeUrl": principal.gestor_home_url,
        "gestorLoginUrl": principal.gestor_login_url,
        "gestorLogoutUrl": principal.gestor_logout_url,
    }


@router.get("/auth/me", tags=["auth"])
def auth_me(
    request: Request,
    response: Response,
    principal: Principal = Depends(current_principal),
):
    response.headers["Cache-Control"] = "no-store"
    marker = principal.sso_marker
    return {
        "name": principal.name,
        "email": principal.email,
        "role": principal.role,
        "roleColor": principal.role_color,
        "institute": principal.institute_id,
        "anoLetivo": principal.academic_year,
        "schoolName": principal.school_name,
        "images": identity.sso_images(
            getattr(request.state, "sso_payload", {})
        ),
        **_gestor_links(principal),
        "ssoVinculada": bool(principal.sso_session_id),
        # O painel so liga a vigia do marcador se o cookie do gestor estiver no navegador (mesmo dominio): ali ele
        # sai assim que o gestor sair. Em localhost o navegador nao o compartilha e a vigia fica desligada.
        "ssoMarcador": {"cookie": marker[0], "valor": marker[1]} if marker else None,
    }


@router.get("/auth/images/boletim", tags=["auth"])
def auth_boletim_logo(
    request: Request,
    principal: Principal = Depends(current_principal),
):
    """Entrega a marca de boletim da sessao atual para uso em PDFs no navegador."""
    del principal
    images = identity.sso_images(getattr(request.state, "sso_payload", {}))
    url = images.get("logos", {}).get("boletim")
    if not url:
        raise HTTPException(404, "Logo de boletim nao configurada para este instituto.")

    try:
        upstream = requests.get(
            url,
            headers={"Accept": "image/png,image/jpeg", "User-Agent": "KeepEdu-Performance/1"},
            timeout=10,
        )
    except requests.RequestException as error:
        raise HTTPException(502, "Nao foi possivel carregar a logo de boletim.") from error

    media_type = upstream.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
    if upstream.status_code != 200 or media_type not in {"image/png", "image/jpeg"}:
        raise HTTPException(502, "A logo de boletim configurada nao e uma imagem valida.")
    if len(upstream.content) > 2 * 1024 * 1024:
        raise HTTPException(502, "A logo de boletim excede o tamanho permitido.")

    return Response(
        content=upstream.content,
        media_type=media_type,
        headers={"Cache-Control": "private, no-store", "Content-Disposition": "inline"},
    )


@router.get("/sso/status", tags=["auth"])
def sso_status(
    response: Response,
    principal: Principal = Depends(session_principal),
):
    """Estado do vinculo com a sessao central (so leitura, nunca o id da sessao). Responde mesmo com a linha ja encerrada, para a
    verificacao mostrar "ausente"."""
    response.headers["Cache-Control"] = "no-store"
    return identity.sso_status(principal.sso_session_id)


@router.post("/auth/logout", tags=["auth"])
def auth_logout(
    principal: Principal | None = Depends(optional_session_principal),
):
    """Encerra a sessao central do SSO (o painel apaga o token do localStorage). Idempotente: sem sessao
    valida responde 200, e devolve so os links do gestor para o retorno."""
    if principal is None:
        return {"authenticated": False}
    try:
        # Sessao local (sem vinculo) nao tem linha central: remove_central_session ignora o id vazio.
        identity.remove_central_session(principal.sso_session_id)
    except Exception as error:
        raise HTTPException(
            503, "Nao foi possivel encerrar a sessao SSO no servidor."
        ) from error
    return {"authenticated": False, **_gestor_links(principal)}


@router.get("/auth/central-session", tags=["auth"])
def auth_central_session(
    renew: bool = False,
    principal: Principal = Depends(session_principal),
):
    if not principal.sso_session_id:
        # So a sessao local de desenvolvimento vive sem a central; qualquer outra sem vinculo ja nao vale.
        return {"active": local_session_allowed(principal), "platforms": []}
    try:
        payload = identity.central_session(principal.sso_session_id, renew=renew)
        return {
            "active": payload is not None,
            "platforms": (
                identity.platform_menu(principal.sso_session_id, payload=payload)
                if payload
                else []
            ),
        }
    except Exception as error:
        raise HTTPException(
            503, "Nao foi possivel verificar a sessao SSO. Tente novamente."
        ) from error


@router.get("/auth/logout-return", tags=["auth"])
def auth_logout_return(return_url: str = Query("", alias="returnUrl")):
    try:
        return {"redirectTo": identity.gestor_return_url(return_url)}
    except Exception as error:
        raise HTTPException(
            503, "Nao foi possivel confirmar o retorno ao gestor."
        ) from error


@router.get("/alunos", tags=["students"])
def students(
    busca: str = "",
    pagina: int = Query(1, ge=1, le=100_000),
    por_pagina: int = Query(10, alias="porPagina", ge=1, le=50),
    principal: Principal = Depends(require_read),
):
    return list_students(tenant(principal), principal, busca, pagina, por_pagina)


@router.get("/filtros", tags=["students"])
def filters(principal: Principal = Depends(require_read)):
    return list_filters(tenant(principal), principal)


@router.get("/rankings", tags=["rankings"])
def rankings(
    unidade: str = Query(min_length=1),
    serie: str = Query(min_length=1),
    turma: str = "",
    etapa: str = "",
    pagina: int = Query(1, ge=1, le=100_000),
    por_pagina: int = Query(10, alias="porPagina", ge=1, le=50),
    principal: Principal = Depends(require_read),
):
    return list_rankings(
        tenant(principal),
        principal,
        unidade,
        serie,
        turma,
        etapa,
        pagina,
        por_pagina,
    )


@router.get("/alunos/{ra}", tags=["students"])
def student(
    ra: str,
    somente_ranking: bool = Query(False, alias="somenteRanking"),
    atualizar: bool = False,
    principal: Principal = Depends(require_read),
):
    value = find_student(tenant(principal), principal, ra)
    if value is None:
        raise HTTPException(404, "Aluno nao encontrado.")
    if somente_ranking:
        return value
    student_id = value.get("alunoId")
    live = {}
    if student_id:
        try:
            live = live_student_details(int(student_id), principal, atualizar)
        except Exception:
            live = {}
    olympic = (
        olympics.student_details(tenant(principal), int(student_id))
        if student_id
        else {}
    )
    return value | live | olympic


@router.post("/alunos/{ra}/relatorio-academico", tags=["students"])
def student_academic_report(
    ra: str,
    principal: Principal = Depends(require_read),
):
    value = find_student(tenant(principal), principal, ra)
    if value is None:
        raise HTTPException(404, "Aluno nao encontrado.")
    student_id = value.get("alunoId")
    live = {}
    if student_id:
        try:
            live = live_student_details(int(student_id), principal, False)
        except Exception:
            live = {}
    olympic = (
        olympics.student_details(tenant(principal), int(student_id))
        if student_id
        else {}
    )
    try:
        return generate_academic_report(value | live | olympic)
    except RuntimeError as error:
        if "GEMINI_API_KEY" in str(error):
            raise HTTPException(503, "Relatorio por IA nao configurado.") from error
        raise HTTPException(
            502, "Nao foi possivel gerar o relatorio academico."
        ) from error
    except Exception as error:
        raise HTTPException(
            502, "Nao foi possivel gerar o relatorio academico."
        ) from error


@router.get("/inicio/ranking", tags=["overview"])
def initial_ranking(principal: Principal = Depends(require_read)):
    return ranking_overview(tenant(principal), principal)


@router.get("/inicio/olimpiadas", tags=["overview"])
def initial_olympics(principal: Principal = Depends(require_read)):
    return olympics.overview(tenant(principal), principal)


@router.get("/analise-notas/{visao}", tags=["notes"])
def note_analysis(
    visao: str,
    unidade: str = "",
    serie: str = "",
    disciplina: str = "",
    avaliacao: str = "",
    etapa: str = "",
    pagina: int = Query(1, ge=1),
    por_pagina: int = Query(50, alias="porPagina", ge=10, le=100),
    principal: Principal = Depends(require_read),
):
    context = tenant(principal)
    if visao == "filtros":
        return notes.filters(context, principal)
    if visao == "resumo":
        return notes.overview(context, principal)
    if visao == "evolucao":
        if not all((unidade, serie, disciplina, avaliacao)):
            raise HTTPException(
                400, "Unidade, serie, disciplina e avaliacao sao obrigatorias."
            )
        return notes.evolution(
            context, principal, unidade, serie, disciplina, avaliacao
        )
    if visao == "dados":
        if not all((unidade, serie, disciplina, avaliacao, etapa)):
            raise HTTPException(
                400, "Unidade, serie, disciplina, avaliacao e etapa sao obrigatorias."
            )
        return notes.insights(
            context,
            principal,
            unidade,
            serie,
            disciplina,
            avaliacao,
            etapa,
            pagina,
            por_pagina,
        )
    raise HTTPException(404, "Visao invalida.")


@router.get("/lancamento-notas/{visao}", tags=["grade-entry"])
def grade_entries(
    visao: str,
    unidade: str = "",
    serie: str = "",
    turma: str = "",
    etapa: str = "",
    disciplina: str = "",
    avaliacao: str = "",
    principal: Principal = Depends(require_read),
):
    if visao not in grade_entry.VIEWS:
        raise HTTPException(404, "Visao invalida.")
    return grade_entry.view(
        tenant(principal),
        principal,
        visao,
        unidade,
        serie,
        turma,
        etapa,
        disciplina,
        avaliacao,
    )


@router.get("/atualizacoes/global", tags=["updates"])
def global_update_status(principal: Principal = Depends(require_read)):
    return updates.global_status(tenant(principal))


@router.get("/atualizacoes/lancamentos", tags=["updates"])
def grade_update_status(principal: Principal = Depends(require_read)):
    return updates.grade_entry_statuses(tenant(principal), principal)


@router.post("/atualizacoes/lancamentos", status_code=202, tags=["updates"])
def update_grades(
    body: dict[str, str] = Body(),
    principal: Principal = Depends(require_write),
):
    unit = body.get("unidade", "").strip()
    stage = body.get("etapa", "").strip()
    if not unit:
        raise HTTPException(400, "Selecione uma unidade antes de atualizar.")
    if not unit_name_allowed(tenant(principal), principal, unit):
        raise HTTPException(403, "Unidade nao autorizada.")
    if stage and stage not in {"1", "2", "3", "4"}:
        raise HTTPException(400, "Etapa invalida.")
    arguments = ["atualizar-lancamentos", "--unidade", unit]
    if stage:
        arguments.extend(["--etapa", stage])
    try:
        return jobs.submit("grade-entry", arguments, principal)
    except RuntimeError as error:
        raise HTTPException(409, str(error)) from error


@router.post("/atualizacoes/ranking", status_code=202, tags=["updates"])
def update_ranking(
    body: dict[str, str] = Body(),
    principal: Principal = Depends(require_write),
):
    unit = body.get("unidade", "").strip()
    series = body.get("serie", "").strip()
    if not unit or not series:
        raise HTTPException(400, "Unidade e serie sao obrigatorias.")
    if not unit_name_allowed(tenant(principal), principal, unit):
        raise HTTPException(403, "Unidade nao autorizada.")
    if not series_name_allowed(tenant(principal), principal, unit, series):
        raise HTTPException(403, "Serie nao autorizada.")
    try:
        return jobs.submit(
            "ranking",
            ["atualizar-ranking", "--unidade", unit, "--serie", series],
            principal,
        )
    except RuntimeError as error:
        raise HTTPException(409, str(error)) from error


@router.get("/jobs/{job_id}", tags=["updates"])
def job_status(job_id: str, principal: Principal = Depends(require_read)):
    value = jobs.get(job_id, principal)
    if value is None:
        raise HTTPException(404, "Job nao encontrado.")
    return value


app.include_router(router)


def run() -> None:
    import uvicorn

    uvicorn.run(
        "keepedu_performance.api.app:app",
        host=settings.api_host,
        port=settings.api_port,
    )


if __name__ == "__main__":
    run()
