from __future__ import annotations

import importlib.util
import json
import unittest
from datetime import UTC, datetime
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]


def load(name: str, path: Path):
    spec = importlib.util.spec_from_file_location(name, path)
    assert spec and spec.loader
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


candidate = load(
    "wp0024_t02_driver_candidate",
    ROOT / "scripts" / "wp0024-t02-driver-candidate.py",
)
harness = load(
    "audit_core_database_lease_recovery_for_driver_contract",
    ROOT / "scripts" / "audit-core-database-lease-recovery.py",
)


class DriverCandidateTests(unittest.TestCase):
    def setUp(self) -> None:
        self.contract = candidate.load_contract()

    def test_contract_exactly_matches_harness_evidence_keys(self) -> None:
        phase_keys = {
            phase: set(record["keys"])
            for phase, record in self.contract["phases"].items()
        }
        self.assertEqual(harness.EXPECTED_DRIVER_KEYS, phase_keys)
        self.assertEqual(
            "RAILIANCE-WP-0024-T02-SYNTHETIC-01",
            self.contract["contract_id"],
        )

    def test_candidate_receipt_round_trip(self) -> None:
        source = {
            "source_repo": "audit-core",
            "source_revision": "a" * 40,
            "source_path": "scripts/lease-load.py",
            "driver_revision": "sha256:" + "b" * 64,
        }
        receipt = candidate.build_receipt(
            self.contract,
            source,
            "audit-core",
            now=datetime(2026, 8, 22, 14, 0, tzinfo=UTC),
        )
        message = {
            "from_agent": "audit-core",
            "subject": candidate.subject(receipt),
            "body": candidate.canonical(receipt),
        }
        self.assertEqual(receipt, candidate.parse_message(message, self.contract))
        self.assertFalse(receipt["registration_executed_driver"])
        self.assertFalse(receipt["secret_values_observed"])

    def test_wrong_contract_digest_is_rejected(self) -> None:
        receipt = candidate.build_receipt(
            self.contract,
            {
                "source_repo": "audit-core",
                "source_revision": "a" * 40,
                "source_path": "scripts/lease-load.py",
                "driver_revision": "sha256:" + "b" * 64,
            },
            "audit-core",
        )
        receipt["contract_digest"] = "0" * 64
        message = {
            "from_agent": "audit-core",
            "subject": candidate.subject(receipt),
            "body": json.dumps(receipt),
        }
        self.assertIsNone(candidate.parse_message(message, self.contract))


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