#!/usr/bin/env python3
"""Quality Gate: Evidence Pack Roundtrip.

Builds a minimal evidence pack, verifies all outputs exist and validate
against their schemas. Exits 0 on success, 1 on failure.
"""

from __future__ import annotations

import json
import sys
import tempfile
from pathlib import Path

from abi_control_core.sdk.evidence_pack import EvidencePackBuilder
from abi_control_core.sdk.validate import validate_json, SchemaValidationError

RUN_MANIFEST = {
    "schema_version": "run-manifest/1.0",
    "run_id": "aa0e0001",
    "gate": "intent-gate",
    "mode": "exploration",
    "trigger": "ci",
    "started_at": "2026-02-25T00:00:00Z",
    "completed_at": "2026-02-25T00:01:00Z",
    "intent_gate_hash": "sha256:" + "a" * 64,
    "verdict": "pass",
    "summary": {"total": 1, "passed": 1, "failed": 0, "skipped": 0, "blocker": 0},
}


def main() -> int:
    errors: list[str] = []

    with tempfile.TemporaryDirectory() as tmp:
        base = Path(tmp) / "evidence_packs"
        base.mkdir()

        builder = EvidencePackBuilder(base, "aa0e0001")
        builder.set_manifest(RUN_MANIFEST)
        builder.add_artifact(b"gate artifact content")
        summary = builder.finalize()

        pack_dir = Path(summary["pack_dir"])

        # Check manifest.json exists and validates
        manifest_path = pack_dir / "manifest.json"
        if not manifest_path.exists():
            errors.append("manifest.json not created")
        else:
            try:
                data = json.loads(manifest_path.read_text(encoding="utf-8"))
                validate_json(data, "run_manifest.schema.json")
            except SchemaValidationError as e:
                errors.append(f"manifest.json validation failed: {e}")

        # Check hashes.json exists
        hashes_path = pack_dir / "hashes.json"
        if not hashes_path.exists():
            errors.append("hashes.json not created")
        else:
            hashes = json.loads(hashes_path.read_text(encoding="utf-8"))
            if not all(v.startswith("sha256:") for v in hashes.values()):
                errors.append("hashes.json contains non-sha256 entries")

        # Check evidence_pack_manifest.json exists and validates
        ep_path = pack_dir / "evidence_pack_manifest.json"
        if not ep_path.exists():
            errors.append("evidence_pack_manifest.json not created")
        else:
            try:
                data = json.loads(ep_path.read_text(encoding="utf-8"))
                validate_json(data, "evidence_pack_manifest.schema.json")
            except SchemaValidationError as e:
                errors.append(f"evidence_pack_manifest.json validation failed: {e}")

        # Check artifacts dir
        artifacts_dir = pack_dir / "artifacts"
        if not artifacts_dir.exists():
            errors.append("artifacts/ directory not created")
        elif len(list(artifacts_dir.iterdir())) != 1:
            errors.append(f"Expected 1 artifact, found {len(list(artifacts_dir.iterdir()))}")

    if errors:
        print(f"FAIL: {len(errors)} evidence pack error(s):")
        for err in errors:
            print(f"  - {err}")
        return 1

    print("PASS: Evidence pack roundtrip verified")
    return 0


if __name__ == "__main__":
    sys.exit(main())
