#!/usr/bin/env python3
"""Test script for SQLite local storage."""

import os
import tempfile
from datetime import datetime

from auth_pe.storage import LocalStorage


def run_tests():
    print("🧪 Testing Python SQLite Storage\n")
    
    # Create temporary database
    test_db = os.path.join(tempfile.gettempdir(), "lelu-test.db")
    
    # Clean up any existing test database
    if os.path.exists(test_db):
        os.remove(test_db)
    
    with LocalStorage(test_db) as storage:
        print(f"✅ Created storage at: {storage.get_db_path()}\n")
        
        # Test 1: Insert and list audit events
        print("Test 1: Audit Events")
        print("─" * 50)
        
        storage.insert_audit_event({
            "trace_id": "trace-001",
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "actor": "test-bot",
            "action": "read_data",
            "resource": {"type": "document", "id": "123"},
            "confidence_score": 0.95,
            "decision": "allow",
            "reason": "High confidence",
        })
        
        storage.insert_audit_event({
            "trace_id": "trace-002",
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "actor": "test-bot",
            "action": "write_data",
            "resource": {"type": "document", "id": "456"},
            "confidence_score": 0.75,
            "decision": "review",
            "reason": "Medium confidence",
            "downgraded_scope": "read-only",
        })
        
        audit_result = storage.list_audit_events(limit=10)
        print(f"✅ Inserted 2 audit events")
        print(f"✅ Retrieved {len(audit_result['events'])} events")
        print(f"   Total count: {audit_result['count']}")
        
        if audit_result["events"]:
            event = audit_result["events"][0]
            print(f"   Latest event: {event['actor']} → {event['action']} ({event['decision']})")
        print()
        
        # Test 2: Insert and list policies
        print("Test 2: Policies")
        print("─" * 50)
        
        storage.upsert_policy(
            name="test-policy",
            content="package test\nallow = true",
            version="1.0",
        )
        
        storage.upsert_policy(
            name="auth-policy",
            content="package auth\nallow { input.confidence > 0.8 }",
            version="1.1",
        )
        
        policies = storage.list_policies()
        print(f"✅ Inserted 2 policies")
        print(f"✅ Retrieved {len(policies)} policies")
        
        for policy in policies:
            print(f"   - {policy['name']} (v{policy['version']})")
        print()
        
        # Test 3: Get specific policy
        print("Test 3: Get Policy")
        print("─" * 50)
        
        policy = storage.get_policy("test-policy")
        if policy:
            print(f"✅ Retrieved policy: {policy['name']}")
            print(f"   Version: {policy['version']}")
            print(f"   Content length: {len(policy['content'])} chars")
            print(f"   HMAC: {policy['hmac_sha256'][:16]}...")
        else:
            print("❌ Failed to retrieve policy")
        print()
        
        # Test 4: Update policy
        print("Test 4: Update Policy")
        print("─" * 50)
        
        storage.upsert_policy(
            name="test-policy",
            content="package test\nallow = false",
            version="2.0",
        )
        
        updated_policy = storage.get_policy("test-policy")
        if updated_policy and updated_policy["version"] == "2.0":
            print(f"✅ Policy updated successfully")
            print(f"   New version: {updated_policy['version']}")
        else:
            print("❌ Failed to update policy")
        print()
        
        # Test 5: Delete policy
        print("Test 5: Delete Policy")
        print("─" * 50)
        
        deleted = storage.delete_policy("auth-policy")
        remaining_policies = storage.list_policies()
        
        if deleted and len(remaining_policies) == 1:
            print(f"✅ Policy deleted successfully")
            print(f"   Remaining policies: {len(remaining_policies)}")
        else:
            print("❌ Failed to delete policy")
        print()
        
        # Test 6: Query with filters
        print("Test 6: Query with Filters")
        print("─" * 50)
        
        filtered_result = storage.list_audit_events(
            actor="test-bot",
            limit=5
        )
        
        print(f"✅ Filtered query returned {len(filtered_result['events'])} events")
        print(f"   All events from actor: test-bot")
        print()
    
    # Cleanup
    if os.path.exists(test_db):
        os.remove(test_db)
        print("✅ Test database cleaned up")
    
    print("\n🎉 All tests passed!\n")


if __name__ == "__main__":
    try:
        run_tests()
    except Exception as e:
        print(f"❌ Test failed: {e}")
        import traceback
        traceback.print_exc()
        exit(1)
