"""Unit tests for scout/checks/judge_diagnostics.py."""
import math
import os
import sys
import unittest
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import judge_diagnostics as jd


class JudgeDiagnosticsTests(unittest.TestCase):
    def test_prop1_binary64_cancellation_counterexample(self):
        res = jd.selftest()
        self.assertEqual(res["status"], "PASS")
        self.assertAlmostEqual(res["prop1_u_safe"], 1.0, places=12)
        self.assertAlmostEqual(res["prop1_u_naive"], 0.5, places=12)

    def test_lp_exact_covariance_identity_and_lift_correction(self):
        rng = np.random.default_rng(20261123)
        n = 2000
        gold = (rng.random(n) < 0.4).astype(int)
        # Positive shared latent difficulty creates conditional dependence among correct items
        difficulty = rng.normal(0.0, 1.2, size=n)
        sa = 0.8 * gold + difficulty + rng.normal(0.0, 0.5, size=n)
        sb = 0.8 * gold + difficulty + rng.normal(0.0, 0.5, size=n)

        raw = jd.lp_overlap_audit(sa, sb, gold, q=0.2, alpha_lift=0.0)
        self.assertLess(raw["identity_abs_err"], 1e-14)
        self.assertGreater(raw["lp_gap"], 0.05)
        self.assertGreater(raw["lambda_unlab"], 1.2)

        alpha = jd.fit_lp_lift_alpha([raw])
        adj = jd.lp_overlap_audit(sa, sb, gold, q=0.2, alpha_lift=alpha)
        self.assertLess(abs(adj["adj_gap"]), 1e-10)

    def test_rationale_decoupling_and_scaffolding(self):
        terse = ["16/5", "42", "\\boxed{7}"]
        verbose_llm = [
            "### Step 1: Analyze\nLet's compute carefully.\n- First, set x=2.\nTherefore, the answer is \\boxed{3}.",
            "Step 1: Expand terms.\nThus, we obtain \\boxed{99}.",
            "# Solution\n1. Check bounds\n2. Conclude\nHence \\boxed{8}.",
        ]
        asym = jd.scaffolding_asymmetry(terse, verbose_llm)
        self.assertLess(asym["mean_delta_scaff"], -0.2)
        self.assertEqual(asym["frac_rejected_more_scaffolded"], 1.0)

        dec = jd.rationale_decoupling_audit(
            chosen_full_p_yes=[0.8, 0.7, 0.8, 0.3],
            rejected_full_p_yes=[0.2, 0.2, 0.9, 0.4],
            chosen_bare_p_yes=[0.2, 0.25, 0.3, 0.15],
            rejected_bare_p_yes=[0.05, 0.10, 0.05, 0.02],
            threshold=0.5,
        )
        self.assertEqual(dec["pair_win_full"], 0.5)
        self.assertEqual(dec["pair_win_bare"], 1.0)
        self.assertTrue(dec["decoupled"])
        self.assertEqual(dec["bare_correct_reject_rate"], 1.0)

    def test_best_of_n_monotone_for_informative_judge(self):
        pids = np.repeat(np.arange(50), 8)
        gold = np.tile([1, 0, 0, 0, 0, 0, 0, 0], 50)
        scores = gold * 2.0 + np.random.default_rng(7).normal(0, 0.5, size=400)
        b1 = jd.exact_best_of_n_correctness(scores, gold, pids, n_draws=1)
        b8 = jd.exact_best_of_n_correctness(scores, gold, pids, n_draws=8)
        self.assertAlmostEqual(b1, 0.125, places=6)
        self.assertGreater(b8, 0.5)


if __name__ == "__main__":
    unittest.main()
