import json
from pathlib import Path

import numpy as np
import pandas as pd
import pytest

from suite6_reporting import (
    load_shared_feature_schema,
    load_shared_fold_scores,
    load_shared_fold_frame,
    build_transfer_diagnostic,
    summarize_router_frame,
)


def test_load_shared_feature_schema_preserves_exact_previous_shared_schema(tmp_path: Path):
    fold_dir = tmp_path / "fold_6"
    fold_dir.mkdir(parents=True)
    payload = {
        "fold": 6,
        "faculties": ["a", "b"],
        "common_raw_features": ["f1", "f3", "f7"],
        "shared_feature_names": ["f1", "f3", "f7", "committee_mean"],
    }
    (fold_dir / "feature_schema.json").write_text(json.dumps(payload))

    schema = load_shared_feature_schema(tmp_path, 6)

    assert schema["common_raw_features"] == ["f1", "f3", "f7"]
    assert schema["fold"] == 6


def test_load_shared_fold_scores_validates_alignment_and_returns_shared_score(tmp_path: Path):
    fold_dir = tmp_path / "fold_7"
    fold_dir.mkdir(parents=True)
    pd.DataFrame(
        {
            "actual": [0, 1, 0],
            "committee": [0.1, 0.8, 0.2],
            "residual_moe_shared": [0.15, 0.7, 0.25],
        }
    ).to_csv(fold_dir / "faculty_x_scores.csv", index=False)

    out = load_shared_fold_scores(
        tmp_path,
        7,
        "faculty_x",
        expected_y=np.array([0, 1, 0]),
        expected_committee=np.array([0.1, 0.8, 0.2]),
    )

    np.testing.assert_allclose(out, [0.15, 0.7, 0.25])


def test_load_shared_fold_scores_rejects_label_misalignment(tmp_path: Path):
    fold_dir = tmp_path / "fold_6"
    fold_dir.mkdir(parents=True)
    pd.DataFrame(
        {
            "actual": [0, 0],
            "committee": [0.1, 0.2],
            "residual_moe_shared": [0.2, 0.3],
        }
    ).to_csv(fold_dir / "faculty_x_scores.csv", index=False)

    with pytest.raises(ValueError, match="label alignment"):
        load_shared_fold_scores(
            tmp_path,
            6,
            "faculty_x",
            expected_y=np.array([0, 1]),
            expected_committee=np.array([0.1, 0.2]),
        )


def test_build_transfer_diagnostic_reports_local_vs_shared_and_evidence_pattern():
    pooled = pd.DataFrame(
        [
            {"faculty": "IT", "model": "committee", "ap": 0.40, "auc": 0.80, "f2_at_20": 0.50},
            {"faculty": "IT", "model": "residual_moe_shared", "ap": 0.38, "auc": 0.78, "f2_at_20": 0.47},
            {"faculty": "IT", "model": "residual_moe_target_only", "ap": 0.42, "auc": 0.82, "f2_at_20": 0.52},
            {"faculty": "DE", "model": "committee", "ap": 0.30, "auc": 0.85, "f2_at_20": 0.45},
            {"faculty": "DE", "model": "residual_moe_shared", "ap": 0.34, "auc": 0.88, "f2_at_20": 0.49},
            {"faculty": "DE", "model": "residual_moe_target_only", "ap": 0.31, "auc": 0.86, "f2_at_20": 0.46},
        ]
    )
    operational = pd.DataFrame(
        [
            {"faculty": "IT", "model": "committee", "fold": "POOLED", "policy": "fixed", "fbeta": 0.50, "precision": 0.30, "recall": 0.60, "f1": 0.40, "flag_rate": 0.20},
            {"faculty": "IT", "model": "residual_moe_shared", "fold": "POOLED", "policy": "fixed", "fbeta": 0.45, "precision": 0.34, "recall": 0.50, "f1": 0.40, "flag_rate": 0.16},
            {"faculty": "IT", "model": "residual_moe_target_only", "fold": "POOLED", "policy": "fixed", "fbeta": 0.53, "precision": 0.33, "recall": 0.63, "f1": 0.43, "flag_rate": 0.21},
            {"faculty": "DE", "model": "committee", "fold": "POOLED", "policy": "fixed", "fbeta": 0.43, "precision": 0.25, "recall": 0.50, "f1": 0.33, "flag_rate": 0.10},
            {"faculty": "DE", "model": "residual_moe_shared", "fold": "POOLED", "policy": "fixed", "fbeta": 0.47, "precision": 0.28, "recall": 0.54, "f1": 0.37, "flag_rate": 0.10},
            {"faculty": "DE", "model": "residual_moe_target_only", "fold": "POOLED", "policy": "fixed", "fbeta": 0.44, "precision": 0.27, "recall": 0.51, "f1": 0.35, "flag_rate": 0.10},
            {"faculty": "IT", "model": "committee", "fold": "POOLED", "policy": "drift", "fbeta": 0.49, "precision": 0.31, "recall": 0.57, "f1": 0.40, "flag_rate": 0.18},
            {"faculty": "IT", "model": "residual_moe_shared", "fold": "POOLED", "policy": "drift", "fbeta": 0.46},
            {"faculty": "IT", "model": "residual_moe_target_only", "fold": "POOLED", "policy": "drift", "fbeta": 0.51},
            {"faculty": "DE", "model": "committee", "fold": "POOLED", "policy": "drift", "fbeta": 0.44},
            {"faculty": "DE", "model": "residual_moe_shared", "fold": "POOLED", "policy": "drift", "fbeta": 0.48},
            {"faculty": "DE", "model": "residual_moe_target_only", "fold": "POOLED", "policy": "drift", "fbeta": 0.45},
        ]
    )

    out = build_transfer_diagnostic(pooled, operational)
    it = out[out.faculty == "IT"].iloc[0]
    de = out[out.faculty == "DE"].iloc[0]

    assert it["local_minus_shared_ap"] == pytest.approx(0.04)
    assert it["local_minus_shared_f2_20"] == pytest.approx(0.05)
    assert it["local_minus_shared_fixed_f2"] == pytest.approx(0.08)
    assert it["evidence_pattern"] == "LOCAL_STRONGER"
    assert de["evidence_pattern"] == "SHARED_STRONGER"


def test_load_shared_fold_frame_exposes_router_columns_after_alignment(tmp_path: Path):
    fold_dir = tmp_path / "fold_6"
    fold_dir.mkdir(parents=True)
    pd.DataFrame({
        "actual": [0, 1],
        "committee": [0.2, 0.7],
        "residual_moe_shared": [0.25, 0.72],
        "correction_logit": [0.1, -0.2],
        "weight_null": [0.6, 0.1],
        "weight_expert_1": [0.4, 0.9],
        "residual_expert_1": [0.2, -0.3],
    }).to_csv(fold_dir / "faculty_y_scores.csv", index=False)

    df = load_shared_fold_frame(
        tmp_path, 6, "faculty_y",
        expected_y=np.array([0, 1]),
        expected_committee=np.array([0.2, 0.7]),
    )
    assert list(df["weight_null"]) == [0.6, 0.1]
    assert "correction_logit" in df.columns


def test_summarize_router_frame_computes_null_entropy_correction_and_residual_correlation():
    df = pd.DataFrame({
        "weight_null": [0.5, 0.2],
        "weight_expert_1": [0.3, 0.4],
        "weight_expert_2": [0.2, 0.4],
        "correction_logit": [0.2, -0.4],
        "residual_expert_1": [0.1, 0.3],
        "residual_expert_2": [0.2, 0.6],
    })
    out = summarize_router_frame(df)
    assert out["mean_null_weight"] == pytest.approx(0.35)
    assert out["mean_abs_correction"] == pytest.approx(0.3)
    assert out["mean_max_weight"] == pytest.approx((0.5 + 0.4) / 2)
    assert out["mean_pairwise_residual_correlation"] == pytest.approx(1.0)
    assert 0 <= out["normalized_entropy"] <= 1
