from __future__ import annotations

import time
from datetime import datetime, timezone
from typing import Any

import requests

from keepedu_performance.api.auth import Principal
from keepedu_performance.core.config import settings


_cache: dict[str, tuple[float, dict[str, Any]]] = {}


def _number(value: object) -> float | None:
    if value in (None, ""):
        return None
    try:
        parsed = float(value)
        return parsed if parsed >= 0 else None
    except (TypeError, ValueError):
        return None


def _post(
    endpoint: str, data: dict[str, object], principal: Principal
) -> dict[str, Any]:
    if not settings.keepedu_api_key:
        raise RuntimeError("KEEPEDU_API_KEY deve ser configurado no servidor.")
    base = settings.keepedu_base_url_for(
        principal.institute_id, principal.school
    ).rstrip("/")
    url = f"{base}/{endpoint.lstrip('/')}"
    for attempt in range(3):
        try:
            response = requests.post(
                url,
                headers={
                    "Accept": "application/json",
                    "apikey": settings.keepedu_api_key,
                    "institute": principal.institute_id,
                },
                data={key: str(value) for key, value in data.items()},
                timeout=60,
            )
            if response.ok:
                payload = response.json()
                if not isinstance(payload, dict):
                    raise RuntimeError("Resposta KeepEdu invalida.")
                return payload
            if response.status_code not in {429, 500, 502, 503, 504}:
                response.raise_for_status()
        except requests.RequestException:
            if attempt == 2:
                raise
        time.sleep(2**attempt)
    raise RuntimeError(f"KeepEdu nao respondeu em {endpoint}.")


def student_details(
    student_id: int, principal: Principal, refresh: bool = False
) -> dict[str, Any]:
    key = f"{principal.institute_id}:{student_id}:{principal.academic_year}"
    now = time.time()
    cached = _cache.get(key)
    if (
        cached
        and not refresh
        and now - cached[0] < settings.keepedu_details_cache_seconds
    ):
        return cached[1] | {"idadeSegundos": int(now - cached[0]), "origemCache": True}
    attendance = _post(
        settings.keepedu_presenca_endpoint,
        {"aluno_id": student_id, "anoletivo": principal.academic_year},
        principal,
    )
    presence = _number(attendance.get("dias_com_presencas"))
    absence = _number(attendance.get("dias_com_faltas"))
    if presence is None or absence is None:
        months = attendance.get("meses") or []
        presence = sum(_number(month.get("dias_presenca")) or 0 for month in months)
        absence = sum(_number(month.get("dias_falta")) or 0 for month in months)
    endpoint = settings.keepedu_ocorrencia_endpoint
    first = _post(
        endpoint, {"filtro_aluno_id": student_id, "page": 1, "limit": 100}, principal
    )
    occurrences = list(first.get("data") or [])
    pages = int(_number(first.get("total_pages")) or 1)
    for page in range(2, pages + 1):
        occurrences.extend(
            _post(
                endpoint,
                {"filtro_aluno_id": student_id, "page": page, "limit": 100},
                principal,
            ).get("data")
            or []
        )
    counts: dict[str, int] = {}
    descriptions: dict[str, list[str]] = {}
    for occurrence in occurrences:
        name = str(occurrence.get("tipo_nome") or "Sem tipo").strip()
        counts[name] = counts.get(name, 0) + 1
        description = str(occurrence.get("descricao") or "").strip()
        if description:
            descriptions.setdefault(name, []).append(description)
    total = presence + absence
    value = {
        "diasComPresencas": presence,
        "diasComFaltas": absence,
        "frequenciaPercentual": round(presence / total * 100, 2) if total else None,
        "ocorrenciasTotal": len(occurrences),
        "ocorrenciasPorTipo": counts,
        "ocorrenciasDescricoesPorTipo": descriptions,
        "consultadoEm": datetime.now(timezone.utc).isoformat(),
        "idadeSegundos": 0,
        "origemCache": False,
    }
    _cache[key] = (now, value)
    return value
