"""AgenLang CLI — simple command-line interface."""

import sys
import json
import asyncio
from pathlib import Path
import click
from .contract import Contract
from .runtime import Runtime
from cryptography.hazmat.primitives import hmac
from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.hazmat.backends import default_backend

@click.group()
def main():
    """AgenLang — standardized contract substrate for agents."""
    pass

@main.command()
@click.argument("contract_path", type=click.Path(exists=True))
def run(contract_path):
    """Run an AgenLang contract."""
    try:
        contract = Contract.from_file(contract_path)
        runtime = Runtime(contract)
        result, ser = asyncio.run(runtime.execute())

        print("✅ Execution successful!")
        print(f"Goal: {contract.goal}")
        print(f"Result: {result['output']}")
        print("\nSER (audit trail):")
        print(runtime.to_ser_json(ser))

        Path(f"{contract.contract_id}.ser.json").write_text(runtime.to_ser_json(ser))
        print(f"\nSER saved to {contract.contract_id}.ser.json")

    except Exception as e:
        print(f"❌ Error: {e}")
        sys.exit(1)

@main.command()
@click.argument("contract_path", type=click.Path(exists=True))
def validate(contract_path):
    """Validate a contract against the schema."""
    try:
        Contract.from_file(contract_path)
        print("✅ Contract is valid!")
    except Exception as e:
        print(f"❌ Invalid contract: {e}")

@main.command()
@click.argument("execution_id", type=str)
def replay(execution_id):
    """Replay a past execution from the HMAC-protected replay file."""
    replay_path = Path(f"{execution_id}.replay")
    ser_path = Path(f"{execution_id}.ser.json")
    if not replay_path.exists():
        print(f"❌ Replay file not found: {replay_path}")
        sys.exit(1)
    if not ser_path.exists():
        print(f"❌ SER file not found: {ser_path} - needed for key")
        sys.exit(1)

    ser_data = json.loads(ser_path.read_text())
    key_hex = ser_data.get("replay_key")
    if not key_hex:
        print("❌ No replay_key in SER - cannot verify")
        sys.exit(1)
    key = bytes.fromhex(key_hex)

    content = replay_path.read_bytes()
    replay_content = content[:-32]
    received_hmac = content[-32:]

    h = hmac.HMAC(key, SHA256(), backend=default_backend())
    h.update(replay_content)
    expected_hmac = h.finalize()

    if received_hmac != expected_hmac:
        print("❌ Replay integrity check failed - possible tampering!")
        sys.exit(1)

    data = json.loads(replay_content)
    print("✅ Replay integrity verified!")
    print("Replayed steps:")
    for item in data:
        print(f"- Step: {item['step']} Output: {item['output']}")

if __name__ == "__main__":
    main()
