#!/usr/bin/env python3
"""
Receipt Validation CLI

Quick validation of receipt files for buyer demos.

Usage:
    python3 -m helix_cdc.validate artifacts/*.json
    python3 -m helix_cdc.validate artifacts/hw_route.receipt.json
"""

import sys
import json
from pathlib import Path
from typing import Dict, List, Tuple

def validate_receipt(receipt_path: Path) -> Tuple[bool, List[str]]:
    """
    Validate a single receipt file.

    Returns: (passes, issues)
    """
    issues = []

    try:
        with open(receipt_path) as f:
            receipt = json.load(f)
    except Exception as e:
        return False, [f"Failed to load: {e}"]

    # Check required top-level keys
    required_keys = [
        "protocol_version",
        "schema_version",
        "timestamp_utc",
        "claim",
        "provenance",
        "acceptance_gates"
    ]

    for key in required_keys:
        if key not in receipt:
            issues.append(f"Missing required key: {key}")

    # Check provenance fields
    if "provenance" in receipt:
        required_prov = ["git_commit", "impl_sha256"]
        for key in required_prov:
            if key not in receipt["provenance"]:
                issues.append(f"Missing provenance.{key}")

    # Check acceptance gates
    if "acceptance_gates" in receipt:
        if "passes" not in receipt["acceptance_gates"]:
            issues.append("Missing acceptance_gates.passes")
        elif not receipt["acceptance_gates"]["passes"]:
            # AMBER status receipts are allowed to have failing gates
            # (they document known limitations, not failures)
            claim_status = receipt.get("claim", {}).get("status", "")
            if claim_status not in ("AMBER", "YELLOW", "KNOWN_LIMITATION"):
                issues.append("Acceptance gates failed")

    # Check claim status
    if "claim" in receipt:
        if "status" not in receipt["claim"]:
            issues.append("Missing claim.status")

    return len(issues) == 0, issues

def main():
    """Validate receipt files from command line."""
    if len(sys.argv) < 2:
        print("Usage: python3 -m helix_cdc.validate <receipt_file> [...]")
        print("Example: python3 -m helix_cdc.validate artifacts/*.json")
        sys.exit(1)

    receipt_paths = [Path(p) for p in sys.argv[1:]]

    total = len(receipt_paths)
    passed = 0
    failed = 0

    print(f"🔍 Validating {total} receipt(s)...\n")

    for path in receipt_paths:
        if not path.exists():
            print(f"❌ {path.name}: File not found")
            failed += 1
            continue

        passes, issues = validate_receipt(path)

        if passes:
            print(f"✅ {path.name}: PASS")
            passed += 1
        else:
            print(f"❌ {path.name}: FAIL")
            for issue in issues:
                print(f"   - {issue}")
            failed += 1

    print(f"\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
    print(f"📊 Results: {passed}/{total} passed")

    if failed == 0:
        print("✅ All receipts valid")
        sys.exit(0)
    else:
        print(f"❌ {failed} receipt(s) failed validation")
        sys.exit(1)

if __name__ == "__main__":
    main()
