from __future__ import annotations

from collections import Counter
from datetime import datetime, timezone
from typing import Any

import pandas as pd

from keepedu_performance.core.config import settings
from keepedu_performance.core.grade_entry_audit import frame_class_counts
from keepedu_performance.core.logger import logger
from keepedu_performance.core.paths import AUDIT_DIR
from keepedu_performance.core.update_scope import UpdateScope, atomic_write_json
from keepedu_performance.ingestion.keepedu.notas import (
    assess_stage_response,
    fetch_keepedu_notas_por_etapa,
    load_previous_notes,
)


PROBE_FIELDS = (
    "COD_TIPO_PROVA",
    "TIPO_PROVA",
    "AVALIACAO_ID",
    "ORDEM_PROVA",
    "STATUS_ENVIO_TOTVS",
)
COMPARISON_FIELDS = PROBE_FIELDS + (
    "COD_DISCIPLINA",
    "DISCIPLINA",
    "SERIE",
)
BASE_RECORD_FIELDS = ("RA", "CODTURMA", "COD_DISCIPLINA")
ASSESSMENT_RECORD_FIELDS = BASE_RECORD_FIELDS + (
    "COD_TIPO_PROVA",
    "ORDEM_PROVA",
)


def _value_counts(records: list[dict[str, Any]], field: str) -> dict[str, int]:
    values = Counter(
        str(record.get(field) if record.get(field) is not None else "<NULO>").strip()
        or "<VAZIO>"
        for record in records
    )
    return dict(sorted(values.items()))


def _normalized_value(record: dict[str, Any], field: str) -> str:
    value = record.get(field)
    return str(value if value is not None else "<NULO>").strip() or "<VAZIO>"


def _record_counts(
    records: list[dict[str, Any]], fields: tuple[str, ...]
) -> Counter[tuple[str, ...]]:
    return Counter(
        tuple(_normalized_value(record, field) for field in fields)
        for record in records
    )


def _shared_count(left: Counter, right: Counter) -> int:
    return sum((left & right).values())


def _distribution_differences(
    left: list[dict[str, Any]], right: list[dict[str, Any]]
) -> dict[str, dict[str, dict[str, int]]]:
    result = {}
    for field in COMPARISON_FIELDS:
        left_counts = Counter(_value_counts(left, field))
        right_counts = Counter(_value_counts(right, field))
        values = sorted(set(left_counts) | set(right_counts))
        differences = {
            value: {
                "etapa3": left_counts[value],
                "etapa4": right_counts[value],
                "diferenca": right_counts[value] - left_counts[value],
            }
            for value in values
            if left_counts[value] != right_counts[value]
        }
        if differences:
            result[field] = differences
    return result


def compare_stage_records(
    unit_id: int,
    stage3_records: list[dict[str, Any]],
    stage4_records: list[dict[str, Any]],
) -> dict[str, Any]:
    stage3_fields = {field for record in stage3_records for field in record}
    stage4_fields = {field for record in stage4_records for field in record}
    base3 = _record_counts(stage3_records, BASE_RECORD_FIELDS)
    base4 = _record_counts(stage4_records, BASE_RECORD_FIELDS)
    assessment3 = _record_counts(stage3_records, ASSESSMENT_RECORD_FIELDS)
    assessment4 = _record_counts(stage4_records, ASSESSMENT_RECORD_FIELDS)
    note_fields = ASSESSMENT_RECORD_FIELDS + ("NOTA",)
    notes3 = _record_counts(stage3_records, note_fields)
    notes4 = _record_counts(stage4_records, note_fields)
    shared_base = _shared_count(base3, base4)
    shared_assessment = _shared_count(assessment3, assessment4)
    shared_note = _shared_count(notes3, notes4)
    null_differences = {}
    for field in sorted(stage3_fields | stage4_fields):
        null3 = sum(record.get(field) is None for record in stage3_records)
        null4 = sum(record.get(field) is None for record in stage4_records)
        if null3 != null4:
            null_differences[field] = {"etapa3": null3, "etapa4": null4}
    return {
        "unidadeId": unit_id,
        "registros": {"etapa3": len(stage3_records), "etapa4": len(stage4_records)},
        "alunosDistintos": {
            "etapa3": len({_normalized_value(item, "RA") for item in stage3_records}),
            "etapa4": len({_normalized_value(item, "RA") for item in stage4_records}),
        },
        "avaliacoesDistintas": {
            "etapa3": len(
                {_normalized_value(item, "AVALIACAO_ID") for item in stage3_records}
            ),
            "etapa4": len(
                {_normalized_value(item, "AVALIACAO_ID") for item in stage4_records}
            ),
        },
        "correspondencias": {
            "mesmoAlunoTurmaDisciplina": shared_base,
            "mesmoAlunoTurmaDisciplinaTipoOrdem": shared_assessment,
            "mesmaChaveEValorDaNota": shared_note,
            "apenasEtapa3PelaChaveDeAvaliacao": len(stage3_records)
            - shared_assessment,
            "apenasEtapa4PelaChaveDeAvaliacao": len(stage4_records)
            - shared_assessment,
        },
        "camposSomenteEtapa3": sorted(stage3_fields - stage4_fields),
        "camposSomenteEtapa4": sorted(stage4_fields - stage3_fields),
        "nulosDiferentes": null_differences,
        "distribuicoesDiferentes": _distribution_differences(
            stage3_records, stage4_records
        ),
    }


def _registration_hour_counts(records: list[dict[str, Any]]) -> dict[str, int]:
    values = Counter()
    for record in records:
        raw = str(record.get("DATA_CADASTRO") or "").strip()
        values[raw[:13] if raw else "<VAZIO>"] += 1
    return dict(sorted(values.items()))


def build_probe_summary(
    unit_id: int,
    stage: int,
    records: list[dict[str, Any]],
) -> dict[str, Any]:
    scope = UpdateScope(unit_id)
    previous = load_previous_notes(scope)
    return {
        "unidadeId": unit_id,
        "etapa": stage,
        "registros": len(records),
        "codTurmas": frame_class_counts(pd.DataFrame(records)),
        "comparacaoAnterior": assess_stage_response(previous, records, stage),
        "distribuicoes": {
            field: _value_counts(records, field) for field in PROBE_FIELDS
        },
        "dataCadastroPorHora": _registration_hour_counts(records),
    }


def probe_notes_source(unit_ids: list[int], stages: list[int]) -> dict[str, Any]:
    started_at = datetime.now(timezone.utc)
    results = []
    comparisons = []
    for unit_id in sorted(set(unit_ids)):
        records_by_stage = {}
        for stage in sorted(set(stages)):
            records = fetch_keepedu_notas_por_etapa(stage, UpdateScope(unit_id))
            records_by_stage[stage] = records
            results.append(build_probe_summary(unit_id, stage, records))
        if 3 in records_by_stage and 4 in records_by_stage:
            comparisons.append(
                compare_stage_records(
                    unit_id,
                    records_by_stage[3],
                    records_by_stage[4],
                )
            )
    payload = {
        "institutoId": settings.pipeline_tenant_id or settings.keepedu_institute,
        "anoLetivo": settings.keepedu_anoletivo,
        "iniciadoEm": started_at.isoformat(),
        "finalizadoEm": datetime.now(timezone.utc).isoformat(),
        "resultados": results,
        "comparacoesEtapas3e4": comparisons,
    }
    stamp = started_at.strftime("%Y%m%dT%H%M%SZ")
    destination = AUDIT_DIR / "lancamento_notas" / "sondas" / f"sonda_{stamp}.json"
    atomic_write_json(payload, destination)
    logger.success("Sonda da origem salva em {}.", destination)
    return payload
