#!/usr/bin/env python3
"""
LockStock Live API Test
------------------------
Tests the live API to verify capabilities are properly surfaced.

Run with:
    python test_live_api.py
"""

import asyncio
import httpx
import json
from typing import Optional

# Configuration
API_ENDPOINT = "https://lockstock-api-i9kp.onrender.com"
ADMIN_API_KEY = "lsk_admin_0f89affdbfd62c68c7186bf91eb283969f7a163f5834cbf08923eaa9bac97cd5954f63cf7a07ca65168d3cfd54cec72357952c7462e21b5539828a6d788f1d58"


async def test_fleet_endpoint():
    """Test that fleet endpoint now returns capabilities."""
    print("\n" + "=" * 60)
    print("TEST 1: Fleet Endpoint Capabilities")
    print("=" * 60)

    async with httpx.AsyncClient(timeout=30.0) as client:
        response = await client.get(
            f"{API_ENDPOINT}/api/guard/fleet",
            headers={"x-admin-key": ADMIN_API_KEY}
        )

        if response.status_code != 200:
            print(f"FAIL: Fleet endpoint returned {response.status_code}")
            print(f"Response: {response.text}")
            return False

        agents = response.json()
        print(f"Found {len(agents)} agents in fleet")

        # Check if any agent has capabilities
        agents_with_caps = [a for a in agents if a.get("capabilities")]
        print(f"Agents with capabilities: {len(agents_with_caps)}")

        if agents_with_caps:
            print("\nSample agents with capabilities:")
            for agent in agents_with_caps[:3]:
                print(f"  - {agent['agent_id']}: {agent.get('capabilities', [])}")
            return True
        else:
            print("\nWARNING: No agents have capabilities yet")
            print("This could mean:")
            print("  1. Deployment hasn't completed yet")
            print("  2. No agents have been provisioned with capabilities")
            print("  3. The allowed_tasks column is empty in the database")
            return False


async def test_verify_endpoint(agent_id: str, task: str):
    """Test the verify endpoint for a specific agent."""
    print(f"\n" + "=" * 60)
    print(f"TEST 2: Verify Endpoint ({agent_id} -> {task})")
    print("=" * 60)

    async with httpx.AsyncClient(timeout=30.0) as client:
        payload = {
            "client_id": agent_id,
            "task": task.lower(),
            "parent_hash": "0" * 64,
            "state_matrix": {"a11": 1, "a12": 0, "a21": 0, "a22": 1},
            "signature": "test",
            "timestamp": 1737640000,
            "sequence": 1
        }

        response = await client.post(
            f"{API_ENDPOINT}/verify",
            json=payload,
            headers={"Content-Type": "application/json"}
        )

        result = response.json()
        print(f"Response: {json.dumps(result, indent=2)}")

        if result.get("status") == "accepted":
            print(f"\nSUCCESS: Agent is authorized for {task}")
            return True
        else:
            print(f"\nDENIED: {result.get('reason', 'Unknown reason')}")
            return False


async def test_health():
    """Test that the API is healthy."""
    print("\n" + "=" * 60)
    print("TEST 0: API Health Check")
    print("=" * 60)

    async with httpx.AsyncClient(timeout=30.0) as client:
        response = await client.get(f"{API_ENDPOINT}/health")
        result = response.json()
        print(f"Status: {result.get('status')}")
        print(f"Service: {result.get('service')}")
        return result.get("status") == "healthy"


async def main():
    print("""
╔═══════════════════════════════════════════════════════════════╗
║               LOCKSTOCK LIVE API TEST                         ║
╠═══════════════════════════════════════════════════════════════╣
║  Endpoint: {:<49} ║
╚═══════════════════════════════════════════════════════════════╝
""".format(API_ENDPOINT))

    # Run tests
    results = {}

    # Test 0: Health
    results["health"] = await test_health()

    # Test 1: Fleet with capabilities
    results["fleet_caps"] = await test_fleet_endpoint()

    # Test 2: Verify endpoint (if we have an agent)
    # You can customize this with a known agent ID
    test_agent = "agent_5b14f27f_capabilitytest"
    results["verify"] = await test_verify_endpoint(test_agent, "deploy")

    # Summary
    print("\n" + "=" * 60)
    print("SUMMARY")
    print("=" * 60)
    for test_name, passed in results.items():
        status = "PASS" if passed else "FAIL"
        print(f"  {test_name}: {status}")

    all_passed = all(results.values())
    print(f"\nOverall: {'ALL TESTS PASSED' if all_passed else 'SOME TESTS FAILED'}")


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