from __future__ import annotations

import sys
import unittest
from pathlib import Path

STUDY = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(STUDY))

import run_analysis as analysis  # noqa: E402


class StrustEvidenceAuditTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls.config = analysis.load_config()
        cls.source_rows = analysis.load_ledger(cls.config)
        cls.case_rows = analysis.derive_case_rows(cls.source_rows)
        cls.summary = analysis.build_summary(cls.config, cls.case_rows)

    def test_historical_source_is_bound_by_hash(self) -> None:
        source = STUDY / self.config["source"]["path"]
        self.assertEqual(analysis.sha256(source), self.config["source"]["sha256"])

    def test_table_arithmetic_is_derived_from_rows(self) -> None:
        ledger = self.summary["ledger"]
        self.assertEqual(ledger["case_count"], len(self.case_rows))
        self.assertEqual(
            ledger["recorded_passes"],
            sum(row["recorded_status"] == "Pass" for row in self.case_rows),
        )
        self.assertEqual(ledger["recorded_failures"], 2)
        self.assertEqual(ledger["failed_case_ids"], ["T9", "T10"])
        self.assertAlmostEqual(ledger["recorded_pass_rate"], 0.8)

    def test_internal_claim_discrepancy_is_explicit(self) -> None:
        audit = self.summary["internal_consistency_audit"]
        self.assertFalse(audit["consistent"])
        self.assertAlmostEqual(audit["claim_minus_table_percentage_points"], 20.0)

    def test_labels_are_not_recast_as_independent_ground_truth(self) -> None:
        provenance = self.config["ledger"]["label_provenance"].lower()
        self.assertIn("author-reported", provenance)
        self.assertIn("no independent", provenance)
        self.assertNotIn("ground_truth", self.case_rows[0])

    def test_missing_controls_remain_visible(self) -> None:
        inventory = self.config["evidence_inventory"]
        self.assertEqual(sum(item["status"] == "present" for item in inventory), 1)
        self.assertEqual(sum(item["status"] == "missing" for item in inventory), 7)
        self.assertEqual(
            self.summary["classification"],
            "Project case study",
        )


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