#!/usr/bin/env python3
"""
Test OpenAI Agents SDK with LockStock Authentication
-----------------------------------------------------
This script demonstrates how LockStock provides cryptographic
authentication for every tool call in an AI agent workflow.

Prerequisites:
    pip install openai-agents lockstock-integrations

Usage:
    export OPENAI_API_KEY=your-key
    python test_openai_lockstock.py
"""

import asyncio
import os
import sys

# Add parent to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from lockstock_core import LockStockClient


async def main():
    """Test LockStock authentication flow."""

    # Agent credentials (from provisioning)
    agent_id = os.environ.get("LOCKSTOCK_AGENT_ID", "agent_0ca98b33_openai-test-v2")
    secret = os.environ.get("LOCKSTOCK_SECRET")

    # Try to get secret from Liberty vault if not in env
    if not secret:
        try:
            import subprocess
            result = subprocess.run(
                ["liberty", "show", "LOCKSTOCK_OPENAI_TEST_V2_SECRET"],
                capture_output=True, text=True
            )
            if result.returncode == 0:
                secret = result.stdout.strip().split('\n')[-1]
        except Exception as e:
            print(f"Could not get secret from Liberty: {e}")

    if not secret:
        print("ERROR: No LOCKSTOCK_SECRET found")
        print("Set LOCKSTOCK_SECRET env var or ensure Liberty vault has the secret")
        sys.exit(1)

    print("=" * 60)
    print("LockStock Authentication Test")
    print("=" * 60)
    print(f"Agent ID: {agent_id}")
    print(f"Secret: {secret[:16]}...")
    print()

    # Create LockStock client
    client = LockStockClient(
        agent_id=agent_id,
        secret=secret,
        endpoint="https://lockstock-api-i9kp.onrender.com"
    )

    try:
        # Step 1: Bootstrap the agent
        print("Step 1: Bootstrap agent identity")
        print("-" * 40)
        bootstrap_result = await client.bootstrap()
        print(f"  Root hash: {bootstrap_result.get('root_hash', 'N/A')[:32]}...")
        print(f"  Matrix: {bootstrap_result.get('root_matrix', 'N/A')}")
        print()

        # Step 2: Verify a series of tasks
        tasks = [
            ("Heartbeat", "heartbeat - keep-alive check"),
            ("FileRead", "read_file - reading config.json"),
            ("Shell", "run_command - executing ls -la"),
            ("Database", "query_database - SELECT * FROM users"),
            ("Deploy", "deploy - pushing to production"),
        ]

        print("Step 2: Execute authenticated tasks")
        print("-" * 40)

        for task, description in tasks:
            print(f"\n  Task: {description}")
            result = await client.verify(task=task)

            status_icon = "OK" if result.authorized else "DENIED"
            print(f"  Status: [{status_icon}]")
            print(f"  State hash: {client._current_hash[:32]}...")
            print(f"  Sequence: {client._sequence}")

            if not result.authorized:
                print(f"  Reason: {result.reason}")

        print()
        print("=" * 60)
        print("Hash Chain Summary")
        print("=" * 60)
        print(f"Final sequence: {client._sequence}")
        print(f"Final hash: {client._current_hash}")
        print(f"Final matrix: {client._state_matrix.to_dict()}")
        print()
        print("Each task evolved the cryptographic state.")
        print("The hash chain provides irrefutable audit trail.")

    finally:
        await client.close()


if __name__ == "__main__":
    asyncio.run(main())
