"""
Glacis CLI

Usage:
    python -m glacis verify <receipt.json>
"""

import argparse
import json
import sys
from pathlib import Path

from glacis import Glacis
from glacis.models import AttestReceipt, OfflineAttestReceipt


def verify_command(args):
    """Verify a receipt file."""
    receipt_path = Path(args.receipt)

    if not receipt_path.exists():
        print(f"Error: File not found: {receipt_path}", file=sys.stderr)
        sys.exit(1)

    try:
        with open(receipt_path) as f:
            data = json.load(f)
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON: {e}", file=sys.stderr)
        sys.exit(1)

    # Determine receipt type
    if data.get("attestation_id", "").startswith("oatt_"):
        receipt = OfflineAttestReceipt(**data)
        glacis = Glacis(mode="offline")
    else:
        receipt = AttestReceipt(**data)
        glacis = Glacis(mode="online")

    # Verify
    result = glacis.verify(receipt)

    # Output
    print(f"Receipt: {receipt.attestation_id}")
    print(f"Type: {'Offline' if isinstance(receipt, OfflineAttestReceipt) else 'Online'}")
    print()

    if result.valid:
        print("Status: VALID")
        print(f"  Signature: {'PASS' if result.signature_valid else 'FAIL'}")
        if hasattr(result, "proof_valid") and result.proof_valid is not None:
            print(f"  Merkle proof: {'PASS' if result.proof_valid else 'FAIL'}")
    else:
        print("Status: INVALID")
        if hasattr(result, "error"):
            print(f"  Error: {result.error}")
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(
        prog="glacis", description="Glacis CLI - Cryptographic attestation for AI systems"
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    # verify command
    verify_parser = subparsers.add_parser("verify", help="Verify a receipt")
    verify_parser.add_argument("receipt", help="Path to receipt JSON file")
    verify_parser.set_defaults(func=verify_command)

    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()
