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 (
    BRONZE_DIR,
    RAW_DIR,
    ensure_directories,
)
from keepedu_performance.ingestion.keepedu.ocorrencias import (
    OCCURRENCE_COLUMNS,
)


REQUIRED_COLUMNS = OCCURRENCE_COLUMNS + ["DATA_EXTRACAO", "FONTE"]


def transform_keepedu_ocorrencias_bronze() -> pd.DataFrame:
    input_path = RAW_DIR / f"keepedu_ocorrencias_{settings.keepedu_anoletivo}.parquet"
    logger.info(f"Lendo arquivo raw de ocorrencias: {input_path}")
    if not input_path.exists():
        raise FileNotFoundError(f"Arquivo raw nao encontrado: {input_path}")

    df = pd.read_parquet(input_path)
    qtd_antes = len(df)
    logger.info(f"Registros recebidos na camada bronze: {qtd_antes}")
    missing = [column for column in REQUIRED_COLUMNS if column not in df.columns]
    if missing:
        logger.error(f"Validacao bronze encontrou {len(missing)} coluna(s) ausente(s)")
        raise ValueError(f"Colunas ausentes em ocorrencias raw: {missing}")
    df = df[REQUIRED_COLUMNS].copy()

    for column in ["id", "aluno_id", "ano_letivo", "tipo_ocorrencia_id"]:
        df[column] = pd.to_numeric(df[column], errors="raise").astype("int64")
    if (df["ano_letivo"] != settings.keepedu_anoletivo).any():
        raise ValueError("Existem ocorrencias de outro ano letivo.")
    if df["id"].duplicated().any():
        raise ValueError("Existem ocorrencias duplicadas no arquivo raw.")
    tipo_nome = df["tipo_nome"].astype("string").str.strip()
    sem_tipo = tipo_nome.isna() | tipo_nome.eq("")
    qtd_sem_tipo = int(sem_tipo.sum())
    if qtd_sem_tipo:
        logger.warning(
            f"Ocorrencias sem tipo_nome preenchidas como 'sem tipo': {qtd_sem_tipo}"
        )
    df["tipo_nome"] = tipo_nome.mask(sem_tipo, "sem tipo")

    result = df.sort_values(["aluno_id", "id"]).reset_index(drop=True)
    logger.info(f"Registros validos na camada bronze: {len(result)}")
    logger.info(f"Registros removidos na camada bronze: {qtd_antes - len(result)}")
    return result


def save_keepedu_ocorrencias_bronze(df: pd.DataFrame) -> None:
    output_path = (
        BRONZE_DIR / f"keepedu_ocorrencias_{settings.keepedu_anoletivo}.parquet"
    )
    logger.info(f"Salvando arquivo bronze de ocorrencias: {output_path}")
    df.to_parquet(output_path, index=False)
    logger.success(
        f"Arquivo bronze de ocorrencias salvo com {len(df)} registros: {output_path}"
    )


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


if __name__ == "__main__":
    main()
