from __future__ import annotations

import math
from typing import Any

from keepedu_performance.api.auth import Principal, academic_allowed
from keepedu_performance.api.repository import Tenant
from keepedu_performance.api.storage import (
    legacy_gold_file,
    load_merged_partitions,
    read_json,
)


EXCLUDED = {"5", "18", "19", "34", "41", "ASC", "EXB", "EXTRA BIM", "EXTRA-BIM"}
ALL = "__all__"


def load_notes(tenant: Tenant) -> dict[str, Any]:
    dataset = load_merged_partitions(
        tenant, "notas", ("classPositions", "evaluatedStudents", "lowGrades")
    )
    if dataset is not None:
        return dataset
    legacy = legacy_gold_file(tenant, f"analise_notas_{tenant.year}.json")
    if legacy:
        payload = read_json(legacy)
        if isinstance(payload, dict):
            return payload
    return {
        "anoLetivo": tenant.year,
        "generatedAt": "",
        "notasCorte": [],
        "classPositions": [],
        "evaluatedStudents": [],
        "lowGrades": [],
    }


def _allowed(row: dict[str, Any], principal: Principal) -> bool:
    assessment = str(row.get("codAvaliacao", "")).upper()
    name = str(row.get("avaliacao", "")).upper()
    return (
        academic_allowed(principal, row.get("codColigada"), row.get("serie"))
        and assessment not in EXCLUDED
        and name not in EXCLUDED
    )


def _matches(value: object, selected: str) -> bool:
    return selected == ALL or str(value or "") == selected


def filters(tenant: Tenant, principal: Principal) -> dict[str, Any]:
    dataset = load_notes(tenant)
    rows = [row for row in dataset["classPositions"] if _allowed(row, principal)]
    result = []
    for unit in sorted({str(row["unidade"]) for row in rows}):
        series_items = []
        for series in sorted(
            {str(row["serie"]) for row in rows if row["unidade"] == unit}
        ):
            subjects = []
            subject_rows = [
                row for row in rows if row["unidade"] == unit and row["serie"] == series
            ]
            for code in sorted({str(row["codDisciplina"]) for row in subject_rows}):
                selected = [
                    row for row in subject_rows if str(row["codDisciplina"]) == code
                ]
                assessments = []
                for assessment_code in sorted(
                    {str(row["codAvaliacao"]) for row in selected}
                ):
                    assessment_rows = [
                        row
                        for row in selected
                        if str(row["codAvaliacao"]) == assessment_code
                    ]
                    assessments.append(
                        {
                            "codigo": assessment_code,
                            "nome": str(assessment_rows[0]["avaliacao"]),
                            "etapas": [
                                {
                                    "codigo": stage,
                                    "nome": str(
                                        next(
                                            row["etapa"]
                                            for row in assessment_rows
                                            if str(row["codEtapa"]) == stage
                                        )
                                    ),
                                }
                                for stage in sorted(
                                    {str(row["codEtapa"]) for row in assessment_rows}
                                )
                            ],
                        }
                    )
                subjects.append(
                    {
                        "codigo": code,
                        "nome": str(selected[0]["disciplina"]),
                        "avaliacoes": assessments,
                    }
                )
            series_items.append({"nome": series, "disciplinas": subjects})
        result.append({"nome": unit, "series": series_items})
    return {
        "anoLetivo": dataset.get("anoLetivo", tenant.year),
        "notasCorte": dataset.get("notasCorte", []),
        "unidades": result,
    }


def overview(tenant: Tenant, principal: Principal) -> dict[str, Any]:
    dataset = load_notes(tenant)
    groups: dict[str, dict[str, Any]] = {}
    for row in dataset["classPositions"]:
        quantity = int(row.get("quantidadeNotas") or 0)
        if not _allowed(row, principal) or quantity <= 0:
            continue
        code = str(row["codAvaliacao"])
        item = groups.setdefault(
            code,
            {
                "codigo": code,
                "nome": row["avaliacao"],
                "soma": 0.0,
                "corte": 0.0,
                "quantidade": 0,
            },
        )
        item["soma"] += float(row["mediaTurma"]) * quantity
        item["corte"] += float(row["notaCorte"]) * quantity
        item["quantidade"] += quantity
    assessments = [
        {
            "codigo": item["codigo"],
            "nome": item["nome"],
            "media": round(item["soma"] / item["quantidade"], 2),
            "mediaAprovacao": round(item["corte"] / item["quantidade"], 2),
            "quantidadeNotas": item["quantidade"],
        }
        for item in groups.values()
    ]
    assessments.sort(key=lambda item: str(item["nome"]))
    return {
        "anoLetivo": dataset.get("anoLetivo", tenant.year),
        "notasCorte": dataset.get("notasCorte", []),
        "avaliacoes": assessments,
    }


def evolution(
    tenant: Tenant,
    principal: Principal,
    unit: str,
    series: str,
    subject: str,
    assessment: str,
) -> dict[str, Any]:
    dataset = load_notes(tenant)
    rows = [
        row
        for row in dataset["classPositions"]
        if _allowed(row, principal)
        and _matches(row.get("unidade"), unit)
        and _matches(row.get("serie"), series)
        and str(row.get("codDisciplina")) == subject
        and str(row.get("codAvaliacao")) == assessment
        and int(row.get("quantidadeNotas") or 0) > 0
    ]
    stages: dict[str, dict[str, Any]] = {}
    for row in rows:
        code = str(row["codEtapa"])
        quantity = int(row["quantidadeNotas"])
        item = stages.setdefault(
            code,
            {
                "codigo": code,
                "nome": row["etapa"],
                "soma": 0.0,
                "corte": 0.0,
                "quantidadeNotas": 0,
                "quantidadeNotasAbaixoCorte": 0,
                "turmas": set(),
            },
        )
        item["soma"] += float(row["mediaTurma"]) * quantity
        item["corte"] += float(row["notaCorte"]) * quantity
        item["quantidadeNotas"] += quantity
        item["quantidadeNotasAbaixoCorte"] += int(
            row.get("quantidadeNotasAbaixoCorte") or 0
        )
        item["turmas"].add((row["unidade"], row["serie"], row["turma"]))
    return {
        "etapas": [
            {
                "codigo": item["codigo"],
                "nome": item["nome"],
                "media": round(item["soma"] / item["quantidadeNotas"], 2),
                "mediaAprovacao": round(item["corte"] / item["quantidadeNotas"], 2),
                "quantidadeNotas": item["quantidadeNotas"],
                "quantidadeNotasAbaixoCorte": item["quantidadeNotasAbaixoCorte"],
                "quantidadeTurmas": len(item["turmas"]),
            }
            for _, item in sorted(stages.items())
        ]
    }


def insights(
    tenant: Tenant,
    principal: Principal,
    unit: str,
    series: str,
    subject: str,
    assessment: str,
    stage: str,
    page: int,
    page_size: int,
) -> dict[str, Any]:
    dataset = load_notes(tenant)

    def matches(row: dict[str, Any]) -> bool:
        return (
            _allowed(row, principal)
            and _matches(row.get("unidade"), unit)
            and _matches(row.get("serie"), series)
            and str(row.get("codDisciplina")) == subject
            and str(row.get("codAvaliacao")) == assessment
            and str(row.get("codEtapa")) == stage
        )

    positions = [row for row in dataset["classPositions"] if matches(row)]
    evaluated_students = [
        row for row in dataset.get("evaluatedStudents", []) if matches(row)
    ]
    if evaluated_students:
        evaluated_student_count = sum(
            int(row.get("quantidadeAlunos") or 0) for row in evaluated_students
        )
    else:
        # Compatibilidade com artefatos anteriores: uma turma pode ter mais de
        # uma ordem da mesma avaliação, então usamos o maior total por turma.
        quantities_by_class: dict[tuple[object, object, object], int] = {}
        for row in positions:
            class_key = (row.get("unidade"), row.get("serie"), row.get("turma"))
            quantities_by_class[class_key] = max(
                quantities_by_class.get(class_key, 0),
                int(row.get("quantidadeNotas") or 0),
            )
        evaluated_student_count = sum(quantities_by_class.values())
    low = sorted(
        (row for row in dataset["lowGrades"] if matches(row)),
        key=lambda row: (float(row.get("nota") or 0), str(row.get("nome") or "")),
    )
    quantity = sum(int(row.get("quantidadeNotas") or 0) for row in positions)
    weighted = sum(
        float(row.get("mediaTurma") or 0) * int(row.get("quantidadeNotas") or 0)
        for row in positions
    )
    ordered = sorted(
        positions,
        key=lambda row: (
            -float(row.get("mediaTurma") or 0),
            str(row.get("turma") or ""),
        ),
    )
    stage_value = (
        None
        if not ordered
        else {
            "codigo": stage,
            "nome": ordered[0].get("etapa"),
            "turmas": [
                {
                    "turma": " · ".join(
                        filter(
                            None,
                            [
                                str(row.get("turma") or ""),
                                str(row.get("serie") or "") if series == ALL else "",
                                str(row.get("unidade") or "") if unit == ALL else "",
                            ],
                        )
                    ),
                    "media": row.get("mediaTurma"),
                    "posicao": index + 1,
                    "totalTurmas": len(ordered),
                    "quantidadeNotas": row.get("quantidadeNotas"),
                    "notaCorte": row.get("notaCorte"),
                    "quantidadeNotasAbaixoCorte": row.get("quantidadeNotasAbaixoCorte"),
                }
                for index, row in enumerate(ordered)
            ],
        }
    )
    start = (page - 1) * page_size
    return {
        "anoLetivo": dataset.get("anoLetivo", tenant.year),
        "generatedAt": dataset.get("generatedAt", ""),
        "notasCorte": sorted({row.get("notaCorte") for row in positions}),
        "quantidadeNotas": quantity,
        "quantidadeAlunosAvaliados": evaluated_student_count,
        "mediaGeral": round(weighted / quantity, 2) if quantity else None,
        "quantidadeNotasAbaixoCorte": len(low),
        "quantidadeTurmas": len(
            {
                (row.get("unidade"), row.get("serie"), row.get("turma"))
                for row in positions
            }
        ),
        "stage": stage_value,
        "lowGrades": low[start : start + page_size],
        "pagination": {
            "page": page,
            "pageSize": page_size,
            "total": len(low),
            "totalPages": max(1, math.ceil(len(low) / page_size)),
        },
    }
