#!/usr/bin/env python3
"""Directly patch the container's llm_call_worker.py - minimal change approach."""

import subprocess
import re

# Read current file from container
r = subprocess.run(['docker', 'exec', 'graphiti-service', 'cat', '/app/llm_call_worker.py'],
                   capture_output=True, text=True)
src = r.stdout

print("=== Current state of llm_call_worker.py ===")
lines = src.split('\n')
for i, line in enumerate(lines):
    print(f"{i:3d}: {line}")

# Strategy: Replace the entire create() method to add reasoning override
old_pattern = r"response = await client\.chat\.completions\.create\(\s*model=payload\['model'\],.*?response_format=\{'type': 'json_object'\},\s*\)"

new_text = """            response = await client.chat.completions.create(
            model=payload['model'],
            messages=payload['messages'],
            temperature=0,
            max_tokens=4096,
            response_format={'type': 'json_object'},
            extra_body={'reasoning': {'effort': 'none'}},
        )"""

if re.search(old_pattern, src, re.DOTALL):
    result = re.sub(old_pattern, new_text, src, flags=re.DOTALL)
    
    # Verify
    if "extra_body={'reasoning': {'effort': 'none'}}" in result:
        print("\n✅ Regex substitution succeeded")
        
        # Write to container
        w = subprocess.run(['docker', 'exec', '-i', 'graphiti-service', 'sh', '-c',
                           'cat > /app/llm_call_worker.py'],
                          input=result.encode(), capture_output=True)
        
        if w.returncode == 0:
            print("✅ Patched container file")
            
            # Sync host source
            with open('/opt/struktur/graphiti/service/llm_call_worker.py', 'w') as f:
                f.write(result)
            print("✅ Synced to host (recreate-fest)")
            
            # Show verify section
            lines_result = result.split('\n')
            print("\n=== Verified sections ===")
            for i, line in enumerate(lines_result):
                if 'extra_body' in line or 'response_format' in line:
                    print(f"{i:3d}: {line}")
        else:
            print(f"❌ Write failed: {w.stderr.decode()}")
    else:
        print("❌ Pattern not found after regex")
else:
    print("❌ Regex pattern not matching")
    raise SystemExit(1)
