import argparse
import importlib

import pandas as pd
import pytest

from keepedu_performance import cli
from keepedu_performance.api.auth import Principal
from keepedu_performance.core.update_scope import UpdateScope


def test_ranking_refresh_does_not_query_or_overwrite_notes(monkeypatch, tmp_path):
    scope = UpdateScope(7, 178)
    notes_root = tmp_path / "silver"
    previous_notes = pd.DataFrame({"RA": ["181768"], "NOTA": [7.0]})
    notes_path = scope.partition_path(notes_root, "keepedu_notas")
    notes_path.parent.mkdir(parents=True)
    previous_notes.to_parquet(notes_path, index=False)

    raw_medias = pd.DataFrame({"layer": ["raw"], "NOTA": [8.0]})
    bronze_medias = pd.DataFrame({"layer": ["bronze"], "NOTA": [8.0]})
    silver_medias = pd.DataFrame({"layer": ["silver"], "NOTA": [8.0]})
    gold_medias = pd.DataFrame({"layer": ["gold"], "NOTA": [8.0]})
    ranking = pd.DataFrame({"RA": ["181768"], "ETAPA": ["4"]})
    published: dict = {}
    saved: list[str] = []

    monkeypatch.setattr(cli, "SILVER_DIR", notes_root)
    monkeypatch.setattr(cli, "ensure_directories", lambda: None)
    monkeypatch.setattr(
        cli,
        "extract_keepedu_notas",
        lambda *_args, **_kwargs: (_ for _ in ()).throw(
            AssertionError("a atualizacao do ranking nao deve consultar lancamentos")
        ),
    )
    monkeypatch.setattr(cli, "extract_keepedu_medias", lambda current: raw_medias)
    monkeypatch.setattr(
        cli, "transform_keepedu_medias_bronze", lambda current: bronze_medias
    )
    monkeypatch.setattr(
        cli, "transform_keepedu_medias_silver", lambda current: silver_medias
    )
    monkeypatch.setattr(cli, "transform_gold_medias", lambda current: gold_medias)
    monkeypatch.setattr(cli, "transform_gold_ranking_alunos", lambda current: ranking)
    monkeypatch.setattr(cli, "validate_media_refresh", lambda *_args: None)
    monkeypatch.setattr(
        cli, "save_raw_medias", lambda *_args: saved.append("raw_medias")
    )
    monkeypatch.setattr(
        cli, "save_bronze_medias", lambda *_args: saved.append("bronze_medias")
    )
    monkeypatch.setattr(
        cli, "save_silver_medias", lambda *_args: saved.append("silver_medias")
    )
    monkeypatch.setattr(
        cli, "save_gold_medias_partition", lambda *_args: saved.append("gold_medias")
    )
    monkeypatch.setattr(
        cli, "save_gold_ranking_partition", lambda *_args: saved.append("ranking")
    )

    def publish(current_scope, notes, medias, current_ranking):
        published.update(
            scope=current_scope,
            notes=notes.copy(),
            medias=medias.copy(),
            ranking=current_ranking.copy(),
        )

    monkeypatch.setattr(cli, "publish_student_partition", publish)
    monkeypatch.setattr(
        cli, "publish_global_series_ranking", lambda: saved.append("ranking_global")
    )
    monkeypatch.setattr(cli, "_write_status", lambda *_args: None)

    returned_raw_medias = cli.update_ranking_academic(scope)

    assert saved == [
        "raw_medias",
        "bronze_medias",
        "silver_medias",
        "gold_medias",
        "ranking",
        "ranking_global",
    ]
    assert published["scope"] == scope
    pd.testing.assert_frame_equal(published["notes"], previous_notes)
    pd.testing.assert_frame_equal(published["medias"], gold_medias)
    pd.testing.assert_frame_equal(published["ranking"], ranking)
    pd.testing.assert_frame_equal(pd.read_parquet(notes_path), previous_notes)
    pd.testing.assert_frame_equal(returned_raw_medias, raw_medias)


def test_academic_refresh_passes_raw_bulletin_to_grade_entry(monkeypatch):
    scope = UpdateScope(7, 178)
    unit_notes = pd.DataFrame({"RA": ["181768"]})
    raw_bulletin = pd.DataFrame(
        {"RA": ["181768"], "ABREVIACAO_AVALIACAO": ["LR14"]}
    )
    received: dict = {}
    monkeypatch.setattr(cli, "ensure_directories", lambda: None)
    monkeypatch.setattr(cli, "extract_keepedu_notas", lambda current: unit_notes)
    monkeypatch.setattr(cli, "extract_keepedu_medias", lambda current: raw_bulletin)
    monkeypatch.setattr(
        cli,
        "update_ranking_academic",
        lambda *_args, **_kwargs: raw_bulletin,
    )

    def update_notes(current_scope, notes, bulletin):
        received.update(scope=current_scope, notes=notes, bulletin=bulletin)

    monkeypatch.setattr(cli, "_update_notes_academic", update_notes)

    cli.update_academic(scope)

    assert received["scope"] == scope
    pd.testing.assert_frame_equal(received["notes"], unit_notes)
    pd.testing.assert_frame_equal(received["bulletin"], raw_bulletin)


def test_academic_refresh_updates_ranking_when_notes_source_failed(monkeypatch):
    scope = UpdateScope(7, 178)
    source_error = RuntimeError("resposta parcial de notas")
    raw_bulletin = pd.DataFrame({"RA": ["181768"]})
    ranking_updates: list[tuple[UpdateScope, bool, pd.DataFrame]] = []
    cli._NOTES_ERRORS_BY_UNIT[scope.unidade_id] = source_error
    monkeypatch.setattr(cli, "ensure_directories", lambda: None)
    monkeypatch.setattr(cli, "extract_keepedu_medias", lambda current: raw_bulletin)
    monkeypatch.setattr(
        cli,
        "update_ranking_academic",
        lambda current, refresh_global_ranking, raw_medias_source: ranking_updates.append(
            (current, refresh_global_ranking, raw_medias_source)
        ),
    )

    try:
        with pytest.raises(RuntimeError, match="resposta parcial"):
            cli.update_academic(scope)
    finally:
        cli._NOTES_ERRORS_BY_UNIT.clear()

    assert len(ranking_updates) == 1
    assert ranking_updates[0][:2] == (scope, False)
    pd.testing.assert_frame_equal(ranking_updates[0][2], raw_bulletin)


def test_academic_refresh_keeps_notes_when_ranking_fails(monkeypatch):
    scope = UpdateScope(7, 178)
    unit_notes = pd.DataFrame({"RA": ["181768"]})
    raw_bulletin = pd.DataFrame({"RA": ["181768"]})
    notes_updates: list[tuple[UpdateScope, pd.DataFrame, pd.DataFrame]] = []
    monkeypatch.setattr(cli, "ensure_directories", lambda: None)
    monkeypatch.setattr(cli, "extract_keepedu_notas", lambda current: unit_notes)
    monkeypatch.setattr(cli, "extract_keepedu_medias", lambda current: raw_bulletin)
    monkeypatch.setattr(
        cli,
        "_update_notes_academic",
        lambda current, notes, bulletin: notes_updates.append(
            (current, notes.copy(), bulletin.copy())
        ),
    )
    monkeypatch.setattr(
        cli,
        "update_ranking_academic",
        lambda *_args, **_kwargs: (_ for _ in ()).throw(
            RuntimeError("boletim indisponivel")
        ),
    )

    with pytest.raises(RuntimeError, match="boletim indisponivel"):
        cli.update_academic(scope)

    assert len(notes_updates) == 1
    assert notes_updates[0][0] == scope
    pd.testing.assert_frame_equal(notes_updates[0][1], unit_notes)
    pd.testing.assert_frame_equal(notes_updates[0][2], raw_bulletin)


def test_ranking_command_uses_the_decoupled_refresh(monkeypatch):
    scope = UpdateScope(7, 178)
    refreshed: list[UpdateScope] = []
    monkeypatch.setattr(cli, "resolve_named_scope", lambda unit, series: scope)
    monkeypatch.setattr(cli, "update_ranking_academic", refreshed.append)

    cli._run_command(
        argparse.Namespace(
            command="atualizar-ranking",
            unidade="PROPOSITO JOCKEY",
            serie="2 SERIE",
        )
    )

    assert refreshed == [scope]


def test_parser_accepts_named_ranking_refresh():
    args = cli.parser().parse_args(
        [
            "atualizar-ranking",
            "--unidade",
            "PROPOSITO JOCKEY",
            "--serie",
            "2 SERIE",
        ]
    )

    assert args.command == "atualizar-ranking"
    assert args.unidade == "PROPOSITO JOCKEY"
    assert args.serie == "2 SERIE"


def test_ranking_endpoint_submits_the_decoupled_command(monkeypatch):
    api_app = importlib.import_module("keepedu_performance.api.app")
    submitted: dict = {}
    principal = Principal(
        subject="coordinator",
        institute_id="tenant-test",
        academic_year=2026,
        scopes=("read", "write"),
    )
    monkeypatch.setattr(api_app, "unit_name_allowed", lambda *_args: True)
    monkeypatch.setattr(api_app, "series_name_allowed", lambda *_args: True)

    def submit(kind, arguments, current_principal):
        submitted.update(
            kind=kind,
            arguments=arguments,
            principal=current_principal,
        )
        return {"status": "queued"}

    monkeypatch.setattr(api_app.jobs, "submit", submit)

    result = api_app.update_ranking(
        {"unidade": "PROPOSITO JOCKEY", "serie": "2 SERIE"},
        principal,
    )

    assert result == {"status": "queued"}
    assert submitted == {
        "kind": "ranking",
        "arguments": [
            "atualizar-ranking",
            "--unidade",
            "PROPOSITO JOCKEY",
            "--serie",
            "2 SERIE",
        ],
        "principal": principal,
    }
