import pandas as pd

from keepedu_performance.core.paths import ensure_directories
from keepedu_performance.processing.silver.keepedu.presencas import (
    calculate_attendance_percentage,
)
from keepedu_performance.processing.gold.ocorrencias import (
    aggregate_occurrences,
)


def test_directories_created():
    ensure_directories()
    assert True


def test_calculate_attendance_percentage():
    attendance = pd.DataFrame(
        {
            "DIAS_COM_PRESENCAS": [83, 0, 10],
            "DIAS_COM_FALTAS": [13, 0, 0],
        }
    )

    result = calculate_attendance_percentage(attendance)

    assert result.iloc[0] == 86.46
    assert pd.isna(result.iloc[1])
    assert result.iloc[2] == 100.0


def test_aggregate_occurrences_includes_students_without_occurrences():
    alunos = pd.DataFrame({"ID_KEEPEDU": [10, 20, 30]})
    ocorrencias = pd.DataFrame(
        {
            "ID_OCORRENCIA": [1, 2, 3],
            "ID_KEEPEDU": [10, 10, 20],
            "TIPO_NOME": ["Atraso", "Atraso", "Advertencia"],
            "DESCRICAO": ["Chegou após o sinal", "Segundo atraso", "Sem uniforme"],
        }
    )

    result = aggregate_occurrences(alunos, ocorrencias).set_index("ID_KEEPEDU")

    assert result.loc[10, "OCORRENCIAS_TOTAL"] == 2
    assert result.loc[10, "OCORRENCIAS_POR_TIPO_JSON"] == '{"Atraso":2}'
    assert result.loc[10, "OCORRENCIAS_DESCRICOES_POR_TIPO_JSON"] == (
        '{"Atraso":["Chegou após o sinal","Segundo atraso"]}'
    )
    assert result.loc[20, "OCORRENCIAS_TOTAL"] == 1
    assert result.loc[30, "OCORRENCIAS_TOTAL"] == 0
    assert result.loc[30, "OCORRENCIAS_POR_TIPO_JSON"] == "{}"
    assert result.loc[30, "OCORRENCIAS_DESCRICOES_POR_TIPO_JSON"] == "{}"


def test_aggregate_occurrences_accepts_empty_source():
    alunos = pd.DataFrame({"ID_KEEPEDU": [10]})
    ocorrencias = pd.DataFrame(
        columns=["ID_OCORRENCIA", "ID_KEEPEDU", "TIPO_NOME", "DESCRICAO"]
    )

    result = aggregate_occurrences(alunos, ocorrencias)

    assert result.to_dict(orient="records") == [
        {
            "ID_KEEPEDU": 10,
            "OCORRENCIAS_TOTAL": 0,
            "OCORRENCIAS_POR_TIPO_JSON": "{}",
            "OCORRENCIAS_DESCRICOES_POR_TIPO_JSON": "{}",
        }
    ]
