import pytest
import time
import sys
import os

# Ensure project root is in path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from api_hook_client import ApiHookClient

def test_comms_volume_stress_performance(live_gui):
    """
    Stress test: Inject many session entries and verify performance doesn't degrade.
    """
    client = ApiHookClient()
    
    # 1. Capture baseline
    time.sleep(2.0) # Wait for stability
    baseline_resp = client.get_performance()
    baseline = baseline_resp.get('performance', {})
    baseline_ft = baseline.get('last_frame_time_ms', 0.0)
    
    # 2. Inject 50 "dummy" session entries
    # Role must match DISC_ROLES in gui_legacy.py (User, AI, Vendor API, System)
    large_session = []
    for i in range(50):
        large_session.append({
            "role": "User", 
            "content": f"Stress test entry {i} " * 5,
            "ts": time.time(),
            "collapsed": False
        })
    
    client.post_session(large_session)
    
    # Give it a moment to process UI updates
    time.sleep(1.0)
    
    # 3. Capture stress performance
    stress_resp = client.get_performance()
    stress = stress_resp.get('performance', {})
    stress_ft = stress.get('last_frame_time_ms', 0.0)
    
    print(f"Baseline FT: {baseline_ft:.2f}ms, Stress FT: {stress_ft:.2f}ms")
    
    # If we got valid timing, assert it's within reason
    if stress_ft > 0:
        assert stress_ft < 33.3, f"Stress frame time {stress_ft:.2f}ms exceeds 30fps threshold"
    
    # Ensure the session actually updated
    session_data = client.get_session()
    entries = session_data.get('session', {}).get('entries', [])
    assert len(entries) >= 50, f"Expected at least 50 entries, got {len(entries)}"
