#!/usr/bin/env python3
"""
Test suite for FlowTorch production components.
Validates schemas, auto-Δ, safety, security without running full server.
"""

import os
import sys

# Set GA_NUDGE_FORBID for security tests
os.environ["GA_NUDGE_FORBID"] = "1"

print("=" * 60)
print("FlowTorch Production Components Test Suite")
print("=" * 60)

# Test 1: Schemas
print("\n[1/6] Testing Pydantic schemas...")
try:
    from edge_app.schemas import ChatRequest, QuantOverlay, CDCParams, SignedReceipt

    # Valid request
    req = ChatRequest(
        model="test",
        messages=[{"role": "user", "content": "test"}],
        quant=QuantOverlay(
            cardinality=3,
            state_letter="b",
            control_consent=True
        )
    )
    print(f"  ✓ ChatRequest validation: OK")
    print(f"    - Cardinality: {req.quant.cardinality}")
    print(f"    - State: {req.quant.state_letter}")
    print(f"    - Consent: {req.quant.control_consent}")

    # Invalid state letter should fail
    try:
        bad_req = ChatRequest(
            messages=[{"role": "user", "content": "test"}],
            quant=QuantOverlay(cardinality=3, state_letter="z")
        )
        print(f"  ✗ Validation should have failed for invalid state letter")
        sys.exit(1)
    except Exception:
        print(f"  ✓ Invalid state letter rejected: OK")

except Exception as e:
    print(f"  ✗ Schema test failed: {e}")
    sys.exit(1)

# Test 2: Auto-Δ selector
print("\n[2/6] Testing auto-Δ selector...")
try:
    from edge_app.auto_delta import (
        get_optimal_delta, auto_select_phi0, validate_delta, calculate_phi0
    )

    # Test all cardinalities
    for card in [2, 3, 4, 8]:
        delta = get_optimal_delta(card)
        print(f"  ✓ Cardinality {card}: Δ_opt = {delta}°")

        # Test state mappings
        if card == 3:
            phi0_a, delta_a = auto_select_phi0('a', 3)
            phi0_b, delta_b = auto_select_phi0('b', 3)
            phi0_c, delta_c = auto_select_phi0('c', 3)
            print(f"    Trit mapping: a→{phi0_a:.0f}°, b→{phi0_b:.0f}°, c→{phi0_c:.0f}°")

    # Test 45° exclusion for binary
    if not validate_delta(2, 45):
        print(f"  ✓ Binary 45° exclusion: OK")
    else:
        print(f"  ✗ Binary 45° should be invalid")
        sys.exit(1)

except Exception as e:
    print(f"  ✗ Auto-Δ test failed: {e}")
    sys.exit(1)

# Test 3: Safety monitor
print("\n[3/6] Testing safety monitor...")
try:
    from edge_app.safety import SafetyMonitor, graceful_degrade

    monitor = SafetyMonitor(mi_floor=0.85, jitter_budget=15.0, rate_limit_rpm=300)

    # Test MI tracking (good)
    monitor.record_mi(2.0, 2.0)  # 100% efficiency
    monitor.record_mi(1.95, 2.0)  # 97.5%
    status = monitor.get_status()
    print(f"  ✓ MI tracking: mean={status['mi']['mean']:.3f}")

    # Test jitter tracking
    monitor.record_phi(90.0)
    monitor.record_phi(92.0)
    monitor.record_phi(88.0)
    jitter_ok, mean_jitter = monitor.record_phi(91.0)
    print(f"  ✓ Jitter tracking: mean={mean_jitter:.1f}° (budget: 15°)")

    # Test graceful degradation
    new_card, msg = graceful_degrade(8, "test")
    if new_card == 4:
        print(f"  ✓ Graceful degradation: 8→4 states")
    else:
        print(f"  ✗ Expected degradation to 4, got {new_card}")
        sys.exit(1)

except Exception as e:
    print(f"  ✗ Safety test failed: {e}")
    sys.exit(1)

# Test 4: Security
print("\n[4/6] Testing security...")
try:
    from edge_app.security import (
        check_ga_nudge_forbid, check_control_consent, create_signed_receipt, verify_receipt
    )

    # Test GA-OFF check
    check_ga_nudge_forbid()
    print(f"  ✓ GA-OFF tripwire: ACTIVE (GA_NUDGE_FORBID=1)")

    # Test control consent
    authorized, _ = check_control_consent("127.0.0.1", True)
    if authorized:
        print(f"  ✓ Control consent: localhost authorized")
    else:
        print(f"  ✗ Localhost should be authorized")
        sys.exit(1)

    # Test signed receipts
    receipt = create_signed_receipt(
        phi=90.0,
        R=0.28,
        MI=1.585,
        energy_uJ=1250.0,
        cardinality=3,
        state="b",
        delta_base=90.0,
        phi0_applied=0.0,
        secret_key=b"test_key_32_bytes_long_12345678"
    )

    if "signature" in receipt:
        print(f"  ✓ Signed receipt: signature={receipt['signature'][:16]}...")

    # Verify receipt
    valid = verify_receipt(receipt, b"test_key_32_bytes_long_12345678")
    if valid:
        print(f"  ✓ Receipt verification: VALID")
    else:
        print(f"  ✗ Receipt verification failed")
        sys.exit(1)

except Exception as e:
    print(f"  ✗ Security test failed: {e}")
    sys.exit(1)

# Test 5: Observability
print("\n[5/6] Testing observability...")
try:
    from edge_app.observability import MetricsCollector, health_check

    metrics = MetricsCollector()
    metrics.record_request()
    metrics.record_basin_lock(
        mi=1.585,
        latency=1.2,
        energy=1250.0,
        cardinality=3,
        receipt={"test": "receipt"}
    )

    data = metrics.get_metrics()
    print(f"  ✓ Metrics collection: {data['flowtorch_requests_total']} requests")
    print(f"  ✓ Basin locks: {data['flowtorch_basin_locks_total']}")

    # Health check
    health = health_check()
    print(f"  ✓ Health check: GA-OFF={health['ga_nudge_forbid']}")

except Exception as e:
    print(f"  ✗ Observability test failed: {e}")
    sys.exit(1)

# Test 6: Performance
print("\n[6/6] Testing performance...")
try:
    from edge_app.performance import ConcurrencyGuard, GPUPrewarmer

    guard = ConcurrencyGuard(max_concurrent=4)

    with guard:
        count = guard.get_active_count()
        if count == 1:
            print(f"  ✓ Concurrency guard: {count} active request")
        else:
            print(f"  ✗ Expected 1 active request, got {count}")
            sys.exit(1)

    # GPU prewarm
    prewarmer = GPUPrewarmer()
    status = prewarmer.get_status()
    print(f"  ✓ GPU prewarm: prewarmed={status['prewarmed']}")

except Exception as e:
    print(f"  ✗ Performance test failed: {e}")
    sys.exit(1)

print("\n" + "=" * 60)
print("✓ All tests passed!")
print("=" * 60)
print("\nProduction components ready:")
print("  • Pydantic schemas with validation")
print("  • Auto-Δ selector (validated ranges)")
print("  • Safety monitoring (MI, jitter, rate)")
print("  • Security (GA-OFF, consent, signed receipts)")
print("  • Observability (health, metrics, CDS)")
print("  • Performance (concurrency, prewarm)")
print("\nNext: python3 edge_app/serve_flowtorch_prod.py")
