#!/usr/bin/env python3
import time
import subprocess
import sys
sys.path.append('/Eden/CAPABILITIES')

print("🔍 BOTTLENECK ANALYSIS\n")

# Test 1: Ollama response time
print("1. Testing Ollama generation speed...")
start = time.time()
try:
    result = subprocess.run(
        ['ollama', 'run', 'qwen2.5:7b', 'Generate a simple Python function'],
        capture_output=True,
        text=True,
        timeout=30
    )
    ollama_time = time.time() - start
    print(f"   Ollama time: {ollama_time:.1f}s")
except Exception as e:
    print(f"   ❌ Ollama error: {e}")
    ollama_time = 999

# Test 2: Meta generator validation speed
print("\n2. Testing meta generator speed...")
start = time.time()
try:
    from meta_code_generator import MetaCodeGenerator
    gen = MetaCodeGenerator()
    test_code = """
def test():
    return 42
"""
    gen.validate_code(test_code)
    gen.rate_quality(test_code)
    meta_time = time.time() - start
    print(f"   Meta validation time: {meta_time:.3f}s")
except Exception as e:
    print(f"   ❌ Meta error: {e}")
    meta_time = 999

# Test 3: Quality threshold issue
print("\n3. Checking quality score distribution...")
print("   Reading recent log...")
with open('/Eden/LOGS/eden_asi_clean.log', 'r') as f:
    lines = f.readlines()[-200:]
    
scores = []
rejected = 0
for line in lines:
    if 'Quality: ' in line and '/10' in line:
        try:
            score = int(line.split('Quality: ')[1].split('/')[0])
            scores.append(score)
        except:
            pass
    if 'Quality check:' in line:
        rejected += 1

if scores:
    avg_score = sum(scores) / len(scores)
    print(f"   Average quality: {avg_score:.1f}/10")
    print(f"   Total attempts: {len(scores)}")
    print(f"   Rejected (Q<5): {rejected}")
    print(f"   Success rate: {(len(scores)-rejected)*100//len(scores)}%")

print("\n" + "="*70)
print("BOTTLENECK IDENTIFIED:")
print("="*70)

if ollama_time > 20:
    print("🔴 PRIMARY BOTTLENECK: Ollama generation (>20s per call)")
    print("   Solution: Reduce prompt complexity, shorter timeouts")
elif rejected > len(scores) * 0.5:
    print("🔴 PRIMARY BOTTLENECK: Quality threshold too high")
    print(f"   Solution: Lower threshold from 5/10 to 3/10")
else:
    print("🟢 No major bottleneck - system optimal")

print()
print(f"Total cycle time estimate: {ollama_time + meta_time + 10:.1f}s")
print(f"Capabilities per hour: {3600 / (ollama_time + meta_time + 10):.0f}")
