from __future__ import annotations

import base64
import hashlib
import hmac
import json
import time
import unicodedata
from dataclasses import dataclass
from datetime import date
from functools import lru_cache
from pathlib import Path

import pandas as pd

from fastapi import Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

from keepedu_performance.core.config import settings
from keepedu_performance.core.paths import RUNTIME_ROOT


bearer_scheme = HTTPBearer(auto_error=False)

# Credencial do navegador: token assinado que o painel guarda no localStorage (as abas compartilham) e manda em Authorization: Bearer.
SESSION_TTL_SECONDS = 60 * 60 * 8


@dataclass(frozen=True)
class Principal:
    subject: str
    institute_id: str
    academic_year: int
    school: str = ""
    name: str = ""
    email: str = ""
    role: str = ""
    role_color: str = ""
    school_name: str = ""
    gestor_home_url: str = ""
    gestor_login_url: str = ""
    gestor_logout_url: str = ""
    sso_session_id: str = ""
    sso_marker: tuple[str, str] | None = None
    local_session: bool = False
    service: bool = False
    units: tuple[str, ...] = ()
    user_category: int | None = None
    academic_scopes: tuple[tuple[str, str], ...] = ()
    academic_scope_restricted: bool = False
    scopes: tuple[str, ...] = ("read",)

    def allows_academic(self, unit_code: object, series: object = "") -> bool:
        unit = str(unit_code or "").strip()
        if self.units and unit not in self.units:
            return False
        if not self.academic_scope_restricted:
            return True
        normalized_series = _normalize_academic(series)
        return any(
            allowed_unit == unit and allowed_series == normalized_series
            for allowed_unit, allowed_series in self.academic_scopes
        )

    def allows_unit(self, unit_code: object) -> bool:
        unit = str(unit_code or "").strip()
        if self.units and unit not in self.units:
            return False
        return not self.academic_scope_restricted or any(
            allowed_unit == unit for allowed_unit, _ in self.academic_scopes
        )


def _normalize_academic(value: object) -> str:
    text = unicodedata.normalize("NFKD", str(value or ""))
    return " ".join(
        "".join(character for character in text if not unicodedata.combining(character))
        .casefold()
        .split()
    )


def academic_allowed(
    access: Principal | tuple[str, ...], unit_code: object, series: object = ""
) -> bool:
    if isinstance(access, Principal):
        return access.allows_academic(unit_code, series)
    return not access or str(unit_code or "").strip() in access


def unit_allowed(access: Principal | tuple[str, ...], unit_code: object) -> bool:
    if isinstance(access, Principal):
        return access.allows_unit(unit_code)
    return not access or str(unit_code or "").strip() in access


def _category(value: object) -> int | None:
    try:
        return int(str(value).strip())
    except (TypeError, ValueError):
        return None


def _academic_access(
    payload: dict[str, object], institute: str, academic_year: int
) -> tuple[int | None, tuple[tuple[str, str], ...]]:
    category = _category(payload.get("categoriaUsuario"))
    if category is None and "coorden" in _normalize_academic(payload.get("role")):
        # Compatibilidade segura com cookies emitidos antes de o SSO propagar
        # categoriaUsuario: coordenacao antiga fica restrita ate autenticar de novo.
        category = 3
    if category != 3:
        return category, ()
    allowed_units = settings.dashboard_allowed_unit_codes
    current_year = str(academic_year)
    result: set[tuple[str, str]] = set()
    values = payload.get("escoposAcademicos")
    for item in values if isinstance(values, list) else []:
        if (
            not isinstance(item, dict)
            or str(item.get("anoLetivo") or "").strip() != current_year
        ):
            continue
        unit = str(item.get("codColigada") or "").strip()
        series = _normalize_academic(item.get("serie"))
        if unit and series and (not allowed_units or unit in allowed_units):
            result.add((unit, series))
    if not result:
        result.update(
            _scopes_from_classes(payload, institute, academic_year, allowed_units)
        )
    return category, tuple(sorted(result))


def _dimension_path(institute: str, academic_year: int) -> Path | None:
    if not institute or not all(
        character.isalnum() or character in "_-" for character in institute
    ):
        return None
    year = academic_year
    tenant_path = (
        RUNTIME_ROOT
        / settings.tenant_data_path
        / institute
        / str(year)
        / "gold"
        / f"dim_turmas_{year}.parquet"
    )
    if tenant_path.is_file():
        return tenant_path
    legacy = RUNTIME_ROOT / settings.gold_path / f"dim_turmas_{year}.parquet"
    return (
        legacy
        if institute in settings.keepedu_institute_ids and legacy.is_file()
        else None
    )


@lru_cache(maxsize=32)
def _class_dimension(
    path: str, modified_at: int
) -> dict[int, tuple[int, int, str, str]]:
    del modified_at
    frame = pd.read_parquet(
        path,
        columns=[
            "ID_TURMA_KEEPEDU",
            "ID_SERIE_KEEPEDU",
            "ID_UNIDADE_KEEPEDU",
            "CODCOLIGADA",
            "SERIE",
        ],
    )
    return {
        int(row.ID_TURMA_KEEPEDU): (
            int(row.ID_SERIE_KEEPEDU),
            int(row.ID_UNIDADE_KEEPEDU),
            str(row.CODCOLIGADA).strip(),
            _normalize_academic(row.SERIE),
        )
        for row in frame.itertuples(index=False)
    }


def _scopes_from_classes(
    payload: dict[str, object],
    institute: str,
    academic_year: int,
    allowed_units: tuple[str, ...],
) -> set[tuple[str, str]]:
    assignments: dict[int, tuple[int, int]] = {}
    values = payload.get("turmas")
    for item in values if isinstance(values, list) else []:
        if not isinstance(item, dict):
            continue
        try:
            class_id = int(str(item.get("id") or "0"))
            series_id = int(str(item.get("serieId") or "0"))
            unit_id = int(str(item.get("unidadeId") or "0"))
        except ValueError:
            continue
        if class_id > 0 and series_id > 0 and unit_id > 0:
            assignments[class_id] = (series_id, unit_id)
    path = _dimension_path(institute, academic_year)
    if not assignments or path is None:
        return set()
    dimension = _class_dimension(str(path), path.stat().st_mtime_ns)
    result = set()
    for class_id, expected in assignments.items():
        current = dimension.get(class_id)
        if current is None or current[:2] != expected:
            continue
        _, _, unit_code, series = current
        if unit_code and series and (not allowed_units or unit_code in allowed_units):
            result.add((unit_code, series))
    return result


def _decode_segment(value: str) -> dict[str, object]:
    padding = "=" * (-len(value) % 4)
    return json.loads(base64.urlsafe_b64decode(value + padding))


def create_session_token(payload: dict[str, object], secret: str | None = None) -> str:
    session_secret = secret or settings.session_secret
    if len(session_secret) < 32:
        raise RuntimeError("SESSION_SECRET deve ter pelo menos 32 caracteres.")
    value = {**payload, "expiresAt": int(time.time()) + SESSION_TTL_SECONDS}
    encoded = (
        base64.urlsafe_b64encode(
            json.dumps(value, separators=(",", ":"), ensure_ascii=False).encode()
        )
        .decode()
        .rstrip("=")
    )
    signature = (
        base64.urlsafe_b64encode(
            hmac.new(session_secret.encode(), encoded.encode(), hashlib.sha256).digest()
        )
        .decode()
        .rstrip("=")
    )
    return f"{encoded}.{signature}"


def session_payload(token: str, secret: str | None = None) -> dict[str, object] | None:
    session_secret = secret or settings.session_secret
    try:
        encoded, signature = token.split(".")
        expected = (
            base64.urlsafe_b64encode(
                hmac.new(
                    session_secret.encode(), encoded.encode(), hashlib.sha256
                ).digest()
            )
            .decode()
            .rstrip("=")
        )
        if not hmac.compare_digest(signature, expected):
            return None
        payload = _decode_segment(encoded)
        if not isinstance(payload, dict):
            return None
        return payload if int(payload.get("expiresAt", 0)) > int(time.time()) else None
    except (ValueError, TypeError, json.JSONDecodeError):
        return None


def _sso_marker(value: object) -> tuple[str, str] | None:
    if not isinstance(value, dict):
        return None
    cookie, marker = str(value.get("cookie") or ""), str(value.get("valor") or "")
    return (cookie, marker) if cookie and marker else None


def verify_session_token(token: str, secret: str) -> Principal | None:
    """Validate the HMAC token already issued by the web SSO."""
    try:
        payload = session_payload(token, secret)
        if payload is None:
            return None
        institute = str(payload.get("institute", "")).strip()
        subject = str(payload.get("usuarioId") or payload.get("username") or "").strip()
        academic_year = int(
            payload.get("anoLetivo") or date.today().year
        )
        if not institute or not subject or not 2000 <= academic_year <= 2100:
            return None
        category, academic_scopes = _academic_access(
            payload, institute, academic_year
        )
        return Principal(
            subject=subject,
            institute_id=institute,
            academic_year=academic_year,
            school=str(payload.get("school") or ""),
            name=str(payload.get("name") or ""),
            email=str(payload.get("email") or ""),
            role=str(payload.get("role") or ""),
            role_color=str(payload.get("roleColor") or ""),
            school_name=str(payload.get("schoolName") or ""),
            gestor_home_url=str(payload.get("gestorHomeUrl") or ""),
            gestor_login_url=str(payload.get("gestorLoginUrl") or ""),
            gestor_logout_url=str(payload.get("gestorLogoutUrl") or ""),
            sso_session_id=str(payload.get("ssoSessionId") or ""),
            sso_marker=_sso_marker(payload.get("ssoMarcador")),
            local_session=bool(payload.get("loc")),
            units=settings.dashboard_allowed_unit_codes,
            user_category=category,
            academic_scopes=academic_scopes,
            academic_scope_restricted=category == 3,
            scopes=tuple(
                str(value)
                for value in payload.get("scopes", ["read", "write"])
                if str(value).strip()
            ),
        )
    except (ValueError, TypeError, KeyError, json.JSONDecodeError):
        return None


def _service_principal(token: str) -> Principal | None:
    configured = settings.api_service_tokens
    item = configured.get(token)
    if not isinstance(item, dict):
        return None
    institute = str(item.get("institute", "")).strip()
    try:
        academic_year = int(item.get("anoLetivo") or date.today().year)
    except (TypeError, ValueError):
        return None
    if not institute or not 2000 <= academic_year <= 2100:
        return None
    return Principal(
        subject=str(item.get("subject") or "service-client"),
        institute_id=institute,
        academic_year=academic_year,
        service=True,
        school=str(item.get("school") or ""),
        units=tuple(
            str(value) for value in item.get("units", []) if str(value).strip()
        ),
        scopes=tuple(str(value) for value in item.get("scopes", ["read"])),
    )


def authenticate_token(token: str) -> Principal | None:
    principal = _service_principal(token)
    if principal:
        return principal
    secret = settings.session_secret
    if len(secret) < 32:
        return None
    return verify_session_token(token, secret)


def optional_session_principal(
    credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
) -> Principal | None:
    return authenticate_token(credentials.credentials if credentials else "")


def session_principal(
    principal: Principal | None = Depends(optional_session_principal),
) -> Principal:
    if principal is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Token ausente, expirado ou invalido.",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return principal


def local_session_allowed(principal: Principal) -> bool:
    """A unica sessao que vale sem vinculo com a central: a do login de desenvolvimento, e so com LOCAL_LOGIN ligado."""
    return principal.local_session and settings.local_login


def current_principal(
    request: Request,
    principal: Principal = Depends(session_principal),
) -> Principal:
    if principal.service:
        # Token de servico e uma credencial de maquina configurada no servidor, nao uma sessao de usuario.
        return principal
    if not principal.sso_session_id:
        if local_session_allowed(principal):
            return principal
        raise HTTPException(
            401, "Sessao sem vinculo com o SSO. Entre novamente pelo gestor."
        )
    from keepedu_performance.api import identity

    try:
        active = identity.central_session(principal.sso_session_id)
    except Exception as error:
        raise HTTPException(
            503, "Nao foi possivel verificar a sessao SSO. Tente novamente."
        ) from error
    if active is None:
        raise HTTPException(401, "Sessao SSO encerrada. Entre novamente pelo gestor.")
    request.state.sso_payload = active
    return principal


def require_read(principal: Principal = Depends(current_principal)) -> Principal:
    if "read" not in principal.scopes:
        raise HTTPException(status_code=403, detail="Token sem permissao de leitura.")
    return principal


def require_write(principal: Principal = Depends(current_principal)) -> Principal:
    if "write" not in principal.scopes:
        raise HTTPException(status_code=403, detail="Token sem permissao de escrita.")
    return principal
