import json

import pandas as pd
import pytest

from keepedu_performance.core import metric_refresh_audit as audit
from keepedu_performance.core.update_scope import UpdateScope


def _configure_paths(monkeypatch, tmp_path):
    raw = tmp_path / "raw"
    gold = tmp_path / "gold"
    audit_dir = tmp_path / "audit"
    monkeypatch.setattr(audit, "RAW_DIR", raw)
    monkeypatch.setattr(audit, "GOLD_DIR", gold)
    monkeypatch.setattr(audit, "AUDIT_DIR", audit_dir)
    return raw, gold, audit_dir


def test_media_refresh_blocks_empty_response_after_existing_data(monkeypatch, tmp_path):
    raw, gold, audit_dir = _configure_paths(monkeypatch, tmp_path)
    scope = UpdateScope(20, 165)
    previous = pd.DataFrame({"RA": range(30), "NOTA": [8.0] * 30})
    for root, entity in ((raw, "keepedu_medias"), (gold, "medias_keepedu")):
        path = scope.partition_path(root, entity)
        path.parent.mkdir(parents=True, exist_ok=True)
        previous.to_parquet(path, index=False)

    with pytest.raises(audit.MetricRegressionError, match="medias bloqueada"):
        audit.validate_media_refresh(scope, previous.iloc[0:0], previous.iloc[0:0])

    event = json.loads(
        (audit_dir / "metricas_academicas/auditoria_2026.jsonl")
        .read_text(encoding="utf-8")
        .strip()
    )
    assert event["aceito"] is False
    assert "extracao_de_medias_zerada_apos_historico_positivo" in event["motivos"]


def test_media_refresh_blocks_severe_partial_response(monkeypatch, tmp_path):
    raw, gold, _ = _configure_paths(monkeypatch, tmp_path)
    scope = UpdateScope(20, 165)
    previous = pd.DataFrame({"RA": range(100), "NOTA": [8.0] * 100})
    current = previous.head(40)
    for root, entity in ((raw, "keepedu_medias"), (gold, "medias_keepedu")):
        path = scope.partition_path(root, entity)
        path.parent.mkdir(parents=True, exist_ok=True)
        previous.to_parquet(path, index=False)

    with pytest.raises(audit.MetricRegressionError, match="50_por_cento"):
        audit.validate_media_refresh(scope, current, current)


def test_attendance_blocks_class_that_loses_existing_months(monkeypatch, tmp_path):
    raw, _, audit_dir = _configure_paths(monkeypatch, tmp_path)
    previous = pd.DataFrame(
        {
            "turma_id": [707, 707, 808],
            "presencas": [100, 120, 50],
            "faltas": [10, 12, 5],
        }
    )
    raw.mkdir(parents=True, exist_ok=True)
    previous.to_parquet(
        raw / "keepedu_frequencia_turmas_2026.parquet", index=False
    )
    current = previous[previous["turma_id"].eq(808)].copy()

    with pytest.raises(audit.MetricRegressionError, match="707"):
        audit.validate_attendance_refresh(current, [707, 808])

    event = json.loads(
        (audit_dir / "metricas_academicas/auditoria_2026.jsonl")
        .read_text(encoding="utf-8")
        .strip()
    )
    assert event["aceito"] is False
    assert event["anomalias"][0]["turmaId"] == 707


def test_attendance_ignores_removed_class(monkeypatch, tmp_path):
    raw, _, _ = _configure_paths(monkeypatch, tmp_path)
    previous = pd.DataFrame(
        {"turma_id": [707], "presencas": [100], "faltas": [10]}
    )
    raw.mkdir(parents=True, exist_ok=True)
    previous.to_parquet(
        raw / "keepedu_frequencia_turmas_2026.parquet", index=False
    )
    current = pd.DataFrame(
        {"turma_id": [808], "presencas": [80], "faltas": [8]}
    )

    audit.validate_attendance_refresh(current, [808])
