import pandas as pd
import pytest

from keepedu_performance import cli
from keepedu_performance.core.update_scope import UpdateScope
from keepedu_performance.ingestion.keepedu import alunos, notas


@pytest.fixture(autouse=True)
def keepedu_credentials(monkeypatch):
    monkeypatch.setattr(alunos.settings, "keepedu_api_key", "test-key")
    monkeypatch.setattr(alunos.settings, "keepedu_institute", "test-tenant")


class _Response:
    status_code = 200

    def raise_for_status(self) -> None:
        pass

    def json(self) -> dict:
        return {"notas": []}


class _StudentResponse(_Response):
    def __init__(self, payload: dict):
        self.payload = payload

    def json(self) -> dict:
        return self.payload


def test_notes_request_sends_selective_scope(monkeypatch) -> None:
    captured: dict = {}

    def post(**kwargs):
        captured.update(kwargs)
        return _Response()

    monkeypatch.setattr(notas.requests, "post", post)
    notas.fetch_keepedu_notas_por_etapa(
        2,
        UpdateScope(unidade_id=12, serie_id=34, turma_id=56),
    )

    assert captured["data"] == {
        "anoletivo": notas.settings.keepedu_anoletivo,
        "codetapa": 2,
        "unidade_id": 12,
        "serie_id": 34,
        "turma_id": 56,
    }


def test_notes_extraction_requests_only_selected_stages(monkeypatch) -> None:
    requested: list[int] = []

    def fetch(stage, scope):
        requested.append(stage)
        return [{"codetapa": str(stage)}]

    monkeypatch.setattr(notas, "fetch_keepedu_notas_por_etapa", fetch)
    result = notas.extract_keepedu_notas(UpdateScope(12), etapas=[2])

    assert requested == [2]
    assert result["codetapa"].tolist() == ["2"]


def test_notes_extraction_retries_partial_stage_response(monkeypatch, tmp_path) -> None:
    scope = UpdateScope(12)
    previous_path = (
        tmp_path
        / "keepedu_notas"
        / f"ano={scope.ano_letivo}"
        / "unidade=12"
        / "serie=34"
        / "data.parquet"
    )
    previous_path.parent.mkdir(parents=True)
    pd.DataFrame(
        {
            "codetapa": ["4"] * 40,
            "CODTURMA": ["EF1AM"] * 40,
            "NOTA": [8.0] * 40,
        }
    ).to_parquet(previous_path, index=False)
    responses = [
        [{"codetapa": "4", "CODTURMA": "EF1AM", "NOTA": 8.0} for _ in range(10)],
        [{"codetapa": "4", "CODTURMA": "EF1AM", "NOTA": 8.0} for _ in range(40)],
    ]
    monkeypatch.setattr(notas, "RAW_DIR", tmp_path)
    monkeypatch.setattr(notas.settings, "keepedu_notas_semantic_attempts", 2)
    monkeypatch.setattr(notas.settings, "keepedu_notas_semantic_retry_seconds", 0)
    monkeypatch.setattr(
        notas,
        "fetch_keepedu_notas_por_etapa",
        lambda stage, unit_scope: responses.pop(0),
    )

    result = notas.extract_keepedu_notas(scope, etapas=[4])

    assert len(result) == 40
    assert responses == []


def test_notes_extraction_rejects_persistent_partial_response(
    monkeypatch, tmp_path
) -> None:
    scope = UpdateScope(12)
    previous_path = (
        tmp_path
        / "keepedu_notas"
        / f"ano={scope.ano_letivo}"
        / "unidade=12"
        / "serie=34"
        / "data.parquet"
    )
    previous_path.parent.mkdir(parents=True)
    pd.DataFrame(
        {
            "codetapa": ["4"] * 40,
            "CODTURMA": ["EF1AM"] * 40,
            "NOTA": [8.0] * 40,
        }
    ).to_parquet(previous_path, index=False)
    partial = [{"codetapa": "4", "CODTURMA": "EF1AM", "NOTA": 8.0} for _ in range(10)]
    attempts = 0

    def fetch(stage, unit_scope):
        nonlocal attempts
        attempts += 1
        return partial

    monkeypatch.setattr(notas, "RAW_DIR", tmp_path)
    monkeypatch.setattr(notas.settings, "keepedu_notas_semantic_attempts", 2)
    monkeypatch.setattr(notas.settings, "keepedu_notas_semantic_retry_seconds", 0)
    monkeypatch.setattr(notas, "fetch_keepedu_notas_por_etapa", fetch)

    with pytest.raises(notas.GradeSourceRegressionError, match="etapa=4"):
        notas.extract_keepedu_notas(scope, etapas=[4])

    assert attempts == 2


def test_notes_scope_uses_official_classes_instead_of_series_label(
    monkeypatch, tmp_path
) -> None:
    classes = pd.DataFrame(
        {
            "ID_UNIDADE_KEEPEDU": [6, 6, 6],
            "ID_SERIE_KEEPEDU": [29, 29, 186],
            "CODTURMA": ["EM1AM", "EM1BM", "EM1ADVI"],
        }
    )
    classes.to_parquet(
        tmp_path / f"dim_turmas_{notas.settings.keepedu_anoletivo}.parquet",
        index=False,
    )
    monkeypatch.setattr(notas, "SILVER_DIR", tmp_path)
    source = pd.DataFrame(
        {
            "SERIE": ["1ª SÉRIE", "1ª SÉRIE ADVANCED", "1ª SÉRIE"],
            "CODTURMA": ["EM1ADVI", "EM1BM", "EM1AM"],
            "RA": ["advanced", "regular-b", "regular-a"],
        }
    )

    advanced = notas.filter_keepedu_notas_scope(source, UpdateScope(6, 186))
    regular = notas.filter_keepedu_notas_scope(source, UpdateScope(6, 29))

    assert advanced["RA"].tolist() == ["advanced"]
    assert regular["RA"].tolist() == ["regular-b", "regular-a"]


def test_previous_unit_notes_ignore_classes_stored_in_the_wrong_series(
    monkeypatch, tmp_path
) -> None:
    scope = UpdateScope(7)
    raw_root = tmp_path / "raw"
    silver_root = tmp_path / "silver"
    for series_id, rows in {
        178: [
            {"codetapa": "1", "CODTURMA": "EM2AM", "NOTA": 8.0},
            {"codetapa": "1", "CODTURMA": "EM2ADVI", "NOTA": 9.0},
        ],
        189: [
            {"codetapa": "1", "CODTURMA": "EM2ADVI", "NOTA": 9.0},
        ],
    }.items():
        path = (
            raw_root
            / "keepedu_notas"
            / f"ano={scope.ano_letivo}"
            / "unidade=7"
            / f"serie={series_id}"
            / "data.parquet"
        )
        path.parent.mkdir(parents=True, exist_ok=True)
        pd.DataFrame(rows).to_parquet(path, index=False)
    silver_root.mkdir(parents=True)
    pd.DataFrame(
        {
            "ID_UNIDADE_KEEPEDU": [7, 7],
            "ID_SERIE_KEEPEDU": [178, 189],
            "CODTURMA": ["EM2AM", "EM2ADVI"],
        }
    ).to_parquet(
        silver_root / f"dim_turmas_{scope.ano_letivo}.parquet",
        index=False,
    )
    monkeypatch.setattr(notas, "RAW_DIR", raw_root)
    monkeypatch.setattr(notas, "SILVER_DIR", silver_root)

    previous = notas.load_previous_notes(scope)

    assert previous["CODTURMA"].tolist() == ["EM2AM", "EM2ADVI"]
    assert notas.assess_stage_response(
        previous,
        [
            {"codetapa": "1", "CODTURMA": "EM2AM", "NOTA": 8.0},
            {"codetapa": "1", "CODTURMA": "EM2ADVI", "NOTA": 9.0},
        ],
        1,
    )["inconsistente"] is False


def test_students_reads_every_page(monkeypatch) -> None:
    pages = {
        1: {
            "alunos": [
                {
                    "id": 1,
                    "ra": "A",
                    "nome": "A",
                    "status_label": "Ativo",
                    "turmas": [{"cod_turma": "T1", "status": "Ativo"}],
                }
            ],
            "page": 1,
            "total_pages": 2,
            "total": 2,
        },
        2: {
            "alunos": [
                {
                    "id": 2,
                    "ra": "B",
                    "nome": "B",
                    "status_label": "Ativo",
                    "turmas": [{"cod_turma": "T2", "status": "Ativo"}],
                }
            ],
            "page": 2,
            "total_pages": 2,
            "total": 2,
        },
    }

    def post(**kwargs):
        return _StudentResponse(pages[kwargs["data"]["page"]])

    monkeypatch.setattr(alunos.requests, "post", post)
    result = alunos.extract_keepedu_alunos()

    assert result["ID"].tolist() == [1, 2]
    assert result["CODTURMA"].tolist() == ["T1", "T2"]


def test_professors_catalog_refreshes_all_processing_layers(monkeypatch) -> None:
    calls: list[tuple[str, object]] = []
    raw = pd.DataFrame({"layer": ["raw"]})
    bronze = pd.DataFrame({"layer": ["bronze"]})
    silver = pd.DataFrame({"layer": ["silver"]})

    monkeypatch.setattr(
        cli,
        "extract_keepedu_professores",
        lambda: calls.append(("extract", None)) or raw,
    )
    monkeypatch.setattr(
        cli,
        "save_keepedu_professores_raw",
        lambda value: calls.append(("save_raw", value)),
    )
    monkeypatch.setattr(
        cli,
        "transform_keepedu_professores_bronze",
        lambda: calls.append(("bronze", None)) or bronze,
    )
    monkeypatch.setattr(
        cli,
        "save_keepedu_professores_bronze",
        lambda value: calls.append(("save_bronze", value)),
    )
    monkeypatch.setattr(
        cli,
        "transform_keepedu_professores_silver",
        lambda: calls.append(("silver", None)) or silver,
    )
    monkeypatch.setattr(
        cli,
        "save_keepedu_professores_silver",
        lambda value: calls.append(("save_silver", value)),
    )

    cli.update_professors_catalog()

    assert calls == [
        ("extract", None),
        ("save_raw", raw),
        ("bronze", None),
        ("save_bronze", bronze),
        ("silver", None),
        ("save_silver", silver),
    ]


def test_grade_entry_update_refreshes_professors_before_notes(monkeypatch) -> None:
    scope = UpdateScope(12)

    monkeypatch.setattr(
        cli, "configured_scopes", lambda unit_id: [UpdateScope(unit_id, 34)]
    )

    def stop_after_professors() -> None:
        raise RuntimeError("professors-refreshed")

    monkeypatch.setattr(cli, "update_professors_catalog", stop_after_professors)

    with pytest.raises(RuntimeError, match="professors-refreshed"):
        cli.update_grade_entries(scope)


def test_stage_merge_removes_historical_classes_from_another_series(
    monkeypatch, tmp_path
) -> None:
    scope = UpdateScope(7, 178)
    raw = tmp_path / "raw"
    silver = tmp_path / "silver"
    monkeypatch.setattr(cli, "RAW_DIR", raw)
    monkeypatch.setattr(notas, "SILVER_DIR", silver)
    silver.mkdir(parents=True)
    pd.DataFrame(
        {
            "ID_UNIDADE_KEEPEDU": [7, 7],
            "ID_SERIE_KEEPEDU": [178, 189],
            "CODTURMA": ["EM2AM", "EM2ADVI"],
        }
    ).to_parquet(silver / "dim_turmas_2026.parquet", index=False)
    current = pd.DataFrame(
        {
            "codetapa": ["3", "4", "4"],
            "CODTURMA": ["EM2AM", "EM2AM", "EM2ADVI"],
            "NOTA": [7.0, 8.0, 9.0],
        }
    )
    current_path = scope.partition_path(raw, "keepedu_notas")
    current_path.parent.mkdir(parents=True)
    current.to_parquet(current_path, index=False)
    fresh = pd.DataFrame(
        {"codetapa": ["3"], "CODTURMA": ["EM2AM"], "NOTA": [7.5]}
    )

    merged = cli._merge_stage_partition(scope, fresh, 3)

    assert merged["CODTURMA"].tolist() == ["EM2AM", "EM2AM"]
    assert merged["codetapa"].tolist() == ["4", "3"]


def test_grade_entry_update_also_publishes_evaluation_analysis(monkeypatch) -> None:
    unit_scope = UpdateScope(7)
    series_scope = UpdateScope(7, 178)
    raw_notes = pd.DataFrame({"RA": ["181768"], "NOTA": [8.0]})
    bronze_notes = pd.DataFrame({"layer": ["bronze"]})
    silver_notes = pd.DataFrame({"layer": ["silver"]})
    gold_notes = pd.DataFrame({"layer": ["gold"], "ETAPA": ["4"]})
    published: list[tuple[UpdateScope, pd.DataFrame]] = []

    monkeypatch.setattr(cli, "ensure_directories", lambda: None)
    monkeypatch.setattr(cli, "configured_scopes", lambda unit_id: [series_scope])
    monkeypatch.setattr(cli, "update_professors_catalog", lambda: None)
    monkeypatch.setattr(cli, "extract_keepedu_notas", lambda *_args, **_kwargs: raw_notes)
    monkeypatch.setattr(cli, "filter_keepedu_notas_scope", lambda *_args: raw_notes)
    monkeypatch.setattr(
        cli, "transform_keepedu_notas_bronze", lambda current: bronze_notes
    )
    monkeypatch.setattr(
        cli, "transform_keepedu_notas_silver", lambda current: silver_notes
    )
    monkeypatch.setattr(cli, "transform_gold_notas", lambda current: gold_notes)
    monkeypatch.setattr(cli, "build_grade_entry_partition", lambda *_args: {"ok": True})
    monkeypatch.setattr(cli, "validate_refresh", lambda *_args: None)
    monkeypatch.setattr(cli, "save_raw_notas", lambda *_args: None)
    monkeypatch.setattr(cli, "save_bronze_notas", lambda *_args: None)
    monkeypatch.setattr(cli, "save_silver_notas", lambda *_args: None)
    monkeypatch.setattr(cli, "save_gold_notas_partition", lambda *_args: None)
    monkeypatch.setattr(cli, "atomic_write_json", lambda *_args: None)
    monkeypatch.setattr(
        cli,
        "publish_notes_partition",
        lambda scope, notes: published.append((scope, notes.copy())),
    )
    monkeypatch.setattr(cli, "_write_grade_entry_status", lambda *_args: {})

    cli.update_grade_entries(unit_scope)

    assert len(published) == 1
    assert published[0][0] == series_scope
    pd.testing.assert_frame_equal(published[0][1], gold_notes)
