"""
Demo script to test the persistence layer functionality.
"""

import os
import sys
from datetime import datetime, timedelta

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

from behavioural_contracts.persistence import MetricsStore, SessionLocal, init_db
from behavioural_contracts.persistence.models import AgentPerformance, ContractViolation


def test_persistence_demo():
    """Test all persistence features."""
    print("🚀 Testing BCE Persistence Layer\n")

    # Initialize database
    print("1. Initializing database...")
    init_db()
    print("   ✅ Database initialized\n")

    # Create session
    session = SessionLocal()
    store = MetricsStore(session)

    # Test 1: Record validation metrics
    print("2. Recording validation metrics...")
    agents = ["gpt-4-agent", "claude-agent", "local-agent"]

    for agent_id in agents:
        for i in range(10):
            metric = store.record_validation(
                agent_id=agent_id,
                contract_id="security-contract-v1",
                validation_time_ms=50 + (i * 10),
                token_count=100 + (i * 5),
                cache_hit=(i > 5),
                confidence_score=0.85 + (i * 0.01),
                temperature_used=0.3,
                extra_data={"model_version": f"v1.{i}", "request_id": f"req-{agent_id}-{i}"},
            )
            print(f"   ✅ Recorded metric for {agent_id}: {metric.validation_time_ms}ms")

    print("\n3. Recording security violations...")

    # Test 2: Record violations
    violations_data = [
        (
            "gpt-4-agent",
            "prompt_injection",
            "high",
            0.95,
            "Detected: 'ignore previous instructions'",
        ),
        ("claude-agent", "hallucination", "medium", 0.75, "Confidence drop on empty input"),
        ("local-agent", "pii_leak", "critical", 0.99, "SSN pattern detected in output"),
        ("gpt-4-agent", "prompt_injection", "medium", 0.65, "Suspicious roleplay attempt"),
    ]

    for agent_id, vtype, severity, confidence, detail in violations_data:
        violation = store.record_violation(
            agent_id=agent_id,
            contract_id="security-contract-v1",
            violation_type=vtype,
            severity=severity,
            confidence=confidence,
            detection_details={"description": detail},
        )
        print(f"   ⚠️  {agent_id}: {vtype} ({severity}) - {detail}")

    # Test 3: Query agent metrics
    print("\n4. Querying agent metrics...")

    for agent_id in agents:
        metrics = store.get_agent_metrics(agent_id)
        print(f"\n   📊 Metrics for {agent_id}:")
        print(f"      Total validations: {metrics['total_validations']}")
        print(f"      Avg response time: {metrics['avg_validation_time_ms']:.1f}ms")
        print(f"      Cache hit rate: {metrics['cache_hit_rate']:.1%}")
        print(f"      Total tokens: {metrics['total_tokens']}")
        print(f"      Violations: {metrics['violation_count']}")
        if metrics["violations"]:
            for v in metrics["violations"]:
                print(f"         - {v['type']} ({v['severity']})")

    # Test 4: Check aggregated performance
    print("\n5. Checking aggregated performance...")

    for agent_id in agents:
        perf = session.query(AgentPerformance).filter(AgentPerformance.agent_id == agent_id).first()

        if perf:
            print(f"\n   🎯 Performance for {agent_id}:")
            print(f"      Compliance score: {perf.compliance_score:.1%}")
            print(f"      Total validations: {perf.total_validations}")
            print(f"      Critical violations: {perf.critical_violations}")
            print(f"      High violations: {perf.high_violations}")

    # Test 5: System health
    print("\n6. Checking system health...")
    health = store.get_system_health()

    print(f"   🏥 System Status: {health['status'].upper()}")
    print(f"      Active agents: {health['active_agents']}")
    print(f"      Recent violations: {health['recent_violations']}")
    print(f"      Uptime: {health['uptime_seconds']:.0f} seconds")

    # Test 6: Time-based queries
    print("\n7. Testing time-based queries...")

    # Get metrics for last hour
    one_hour_ago = datetime.utcnow() - timedelta(hours=1)
    recent_metrics = store.get_agent_metrics("gpt-4-agent", start_time=one_hour_ago)
    print(f"   📅 GPT-4 metrics (last hour): {recent_metrics['total_validations']} validations")

    # Test 7: Database persistence
    print("\n8. Testing database persistence...")

    # Check database file exists
    if os.path.exists("data/contracts.db"):
        size = os.path.getsize("data/contracts.db") / 1024  # KB
        print(f"   💾 Database file size: {size:.1f} KB")

    # Count total records
    from behavioural_contracts.persistence.models import MetricRecord

    total_metrics = session.query(MetricRecord).count()
    total_violations = session.query(ContractViolation).count()
    total_agents = session.query(AgentPerformance).count()

    print("   📈 Total records:")
    print(f"      Metrics: {total_metrics}")
    print(f"      Violations: {total_violations}")
    print(f"      Agents: {total_agents}")

    # Cleanup
    session.close()

    print("\n✅ All persistence features working correctly!")
    print("\n💡 Ready for Azure deployment:")
    print("   - Change DATABASE_URL environment variable")
    print("   - Use PostgreSQL connection string")
    print("   - Run alembic migrations")
    print("   - All code remains the same!")


if __name__ == "__main__":
    test_persistence_demo()
