import json
from time import perf_counter

import pandas as pd

from keepedu_performance.core.config import settings
from keepedu_performance.core.logger import logger
from keepedu_performance.core.paths import (
    GOLD_DIR,
    SILVER_DIR,
    ensure_directories,
)


def aggregate_occurrences(
    alunos: pd.DataFrame, ocorrencias: pd.DataFrame
) -> pd.DataFrame:
    required_alunos = {"ID_KEEPEDU"}
    required_ocorrencias = {
        "ID_OCORRENCIA",
        "ID_KEEPEDU",
        "TIPO_NOME",
        "DESCRICAO",
    }
    if not required_alunos.issubset(alunos.columns):
        raise ValueError("A silver de alunos nao possui ID_KEEPEDU.")
    missing = required_ocorrencias.difference(ocorrencias.columns)
    if missing:
        raise ValueError(f"Colunas ausentes em ocorrencias silver: {sorted(missing)}")

    base = alunos[["ID_KEEPEDU"]].drop_duplicates().copy()
    base["ID_KEEPEDU"] = pd.to_numeric(base["ID_KEEPEDU"], errors="raise").astype(
        "int64"
    )
    if ocorrencias.empty:
        base["OCORRENCIAS_TOTAL"] = 0
        base["OCORRENCIAS_POR_TIPO_JSON"] = "{}"
        base["OCORRENCIAS_DESCRICOES_POR_TIPO_JSON"] = "{}"
        return base

    grouped = (
        ocorrencias.groupby(["ID_KEEPEDU", "TIPO_NOME"], dropna=False)
        .size()
        .rename("QUANTIDADE")
        .reset_index()
    )
    totals = grouped.groupby("ID_KEEPEDU")["QUANTIDADE"].sum()
    by_type = grouped.groupby("ID_KEEPEDU")[["TIPO_NOME", "QUANTIDADE"]].apply(
        lambda group: json.dumps(
            {
                str(row.TIPO_NOME): int(row.QUANTIDADE)
                for row in group.itertuples(index=False)
            },
            ensure_ascii=False,
            separators=(",", ":"),
            sort_keys=True,
        )
    )
    descriptions = (
        ocorrencias.assign(
            DESCRICAO=ocorrencias["DESCRICAO"].astype("string").str.strip()
        )
        .dropna(subset=["DESCRICAO"])
        .loc[lambda frame: frame["DESCRICAO"].ne("")]
        .groupby(["ID_KEEPEDU", "TIPO_NOME"], dropna=False)["DESCRICAO"]
        .apply(list)
        .reset_index()
        .groupby("ID_KEEPEDU")[["TIPO_NOME", "DESCRICAO"]]
        .apply(
            lambda group: json.dumps(
                {
                    str(row.TIPO_NOME): row.DESCRICAO
                    for row in group.itertuples(index=False)
                },
                ensure_ascii=False,
                separators=(",", ":"),
                sort_keys=True,
            )
        )
    )
    summary = pd.DataFrame(
        {
            "OCORRENCIAS_TOTAL": totals,
            "OCORRENCIAS_POR_TIPO_JSON": by_type,
            "OCORRENCIAS_DESCRICOES_POR_TIPO_JSON": descriptions,
        }
    ).reset_index()
    result = base.merge(summary, on="ID_KEEPEDU", how="left")
    result["OCORRENCIAS_TOTAL"] = result["OCORRENCIAS_TOTAL"].fillna(0).astype("int64")
    result["OCORRENCIAS_POR_TIPO_JSON"] = result["OCORRENCIAS_POR_TIPO_JSON"].fillna(
        "{}"
    )
    result["OCORRENCIAS_DESCRICOES_POR_TIPO_JSON"] = result[
        "OCORRENCIAS_DESCRICOES_POR_TIPO_JSON"
    ].fillna("{}")
    return result


def transform_gold_ocorrencias() -> pd.DataFrame:
    alunos_path = SILVER_DIR / f"keepedu_alunos_{settings.keepedu_anoletivo}.parquet"
    ocorrencias_path = (
        SILVER_DIR / f"keepedu_ocorrencias_{settings.keepedu_anoletivo}.parquet"
    )
    logger.info(f"Lendo alunos silver: {alunos_path}")
    alunos = pd.read_parquet(alunos_path)
    logger.info(f"Lendo ocorrencias silver: {ocorrencias_path}")
    ocorrencias = pd.read_parquet(ocorrencias_path)
    logger.info(
        f"Gerando resumo gold para {len(alunos)} alunos e "
        f"{len(ocorrencias)} ocorrencias"
    )
    result = aggregate_occurrences(alunos, ocorrencias)
    logger.info(f"Registros gerados na camada gold: {len(result)}")
    return result


def save_gold_ocorrencias(df: pd.DataFrame) -> None:
    output_path = GOLD_DIR / f"ocorrencias_alunos_{settings.keepedu_anoletivo}.parquet"
    logger.info(f"Salvando arquivo gold de ocorrencias: {output_path}")
    df.to_parquet(output_path, index=False)
    logger.success(
        f"Arquivo gold de ocorrencias salvo com {len(df)} alunos: {output_path}"
    )


def main() -> None:
    start = perf_counter()
    ensure_directories()
    save_gold_ocorrencias(transform_gold_ocorrencias())
    logger.info(f"Pipeline finalizada em {perf_counter() - start:.2f} segundos")


if __name__ == "__main__":
    main()
