import json
import tempfile
import unittest
from pathlib import Path

from compile_emergent_skills import compile_candidates, load_receipts


class EmergentSkillCompilerTests(unittest.TestCase):
    def test_repository_receipts_compile_as_candidates_only(self):
        result = compile_candidates(load_receipts())
        self.assertGreaterEqual(result["source_receipt_count"], 4)
        self.assertTrue(result["candidates"])
        for candidate in result["candidates"]:
            self.assertEqual(candidate["enforcement_level"], "CANDIDATE_ONLY")
            self.assertFalse(candidate["hard_block_allowed"])

    def test_conflicting_invariant_text_is_rejected(self):
        receipt = {
            "schema": "guanghu.ops-experience-receipt/v1",
            "receipt_id": "A",
            "intent": "i",
            "scope": "s",
            "input": "i",
            "evidence": ["e"],
            "decision": "d",
            "action": "a",
            "observed_result": "r",
            "correction": "c",
            "invariant_id": "INV-X",
            "invariant": "one",
            "verification": ["v"],
            "receipt_path": "p",
            "promotion_state": "CANDIDATE_ONLY",
            "recorded_at": "2026-07-26T00:00:00Z",
        }
        with self.assertRaises(ValueError):
            compile_candidates([receipt, {**receipt, "receipt_id": "B", "invariant": "two"}])

    def test_missing_fields_fail_closed(self):
        with tempfile.TemporaryDirectory() as directory:
            Path(directory, "bad.json").write_text(json.dumps({"schema": "guanghu.ops-experience-receipt/v1"}))
            with self.assertRaises(ValueError):
                load_receipts(Path(directory))


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