from __future__ import annotations

import json
import unittest
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
REQUEST_SCHEMA = (
    ROOT / "database" / "contracts" / "arr-submit-processing-result-v1.schema.json"
)
RECEIPT_SCHEMA = (
    ROOT
    / "database"
    / "contracts"
    / "arr-submit-processing-result-receipt-v1.schema.json"
)


class DirectContractSchemaTests(unittest.TestCase):
    def test_request_has_exact_four_fields_and_authoritative_payload_ref(self) -> None:
        schema = json.loads(REQUEST_SCHEMA.read_text(encoding="utf-8"))
        expected = {
            "submission_grant",
            "job_id",
            "attempt_no",
            "payload",
        }
        self.assertFalse(schema["additionalProperties"])
        self.assertEqual(set(schema["required"]), expected)
        self.assertEqual(set(schema["properties"]), expected)
        self.assertNotIn("payload_sha256", schema["properties"])
        reference = schema["properties"]["payload"]["allOf"][0]["$ref"]
        target = (REQUEST_SCHEMA.parent / reference).resolve()
        self.assertEqual(
            target,
            (
                ROOT
                / "database"
                / "contracts"
                / "arr-direct-legacy-structured-result-v3.schema.json"
            ).resolve(),
        )
        self.assertTrue(target.is_file())

    def test_receipt_is_minimal_terminal_contract(self) -> None:
        schema = json.loads(RECEIPT_SCHEMA.read_text(encoding="utf-8"))
        self.assertFalse(schema["additionalProperties"])
        self.assertEqual(
            set(schema["properties"]),
            set(schema["required"]),
        )
        self.assertEqual(
            schema["properties"]["status"]["enum"],
            ["committed", "already_committed"],
        )


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