#!/usr/bin/env bash
set -Eeuo pipefail

echo "=== Fáze 3: Webapp integrace safe-oi ==="

cd ~/CyberBrain26

# Záloha webapp.py
cp webapp.py webapp.py.bak

# Přidat endpoint pro code execution do webapp.py
python3 <<'PYEOF'
import re

with open("webapp.py", "r") as f:
    content = f.read()

# Najít místo před @app.get("/health")
health_endpoint = '@app.get("/health")'
if health_endpoint in content:
    # Přidat code execution endpoint před health
    code_endpoint = '''
@app.post("/execute")
async def execute_code(request: ChatRequest):
    """Execute code via safe-oi runner."""
    try:
        # Zde by byla integrace s interpreter
        # Pro MVP vracíme placeholder
        return {
            "response": "Code execution MVP - přijde v další iteraci",
            "model": request.model,
            "memory_used": False
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

'''
    content = content.replace(health_endpoint, code_endpoint + health_endpoint)

with open("webapp.py", "w") as f:
    f.write(content)

print("✅ /execute endpoint přidán")
PYEOF

# Vytvořit jednoduchý terminál HTML
cat > static/terminal.html <<'EOF'
<!DOCTYPE html>
<html lang="cs">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CyberBrain26 Terminál</title>
    <style>
        body { background: #0d1117; color: #c9d1d9; font-family: monospace; margin: 0; padding: 20px; }
        #output { white-space: pre-wrap; margin-bottom: 20px; }
        #input { background: #161b22; border: 1px solid #30363d; color: #c9d1d9; padding: 10px; width: 100%; box-sizing: border-box; }
        .prompt { color: #58a6ff; }
    </style>
</head>
<body>
    <h1>🔒 CyberBrain26 Safe-oi Terminál</h1>
    <div id="output"></div>
    <input type="text" id="input" placeholder="Zadej příkaz..." autofocus>
    <script>
        const output = document.getElementById('output');
        const input = document.getElementById('input');
        
        input.addEventListener('keypress', async (e) => {
            if (e.key === 'Enter') {
                const cmd = input.value;
                output.innerHTML += '<div class="prompt">🧑 ' + cmd + '</div>';
                input.value = '';
                
                try {
                    const resp = await fetch('/execute', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({message: cmd, model: 'gemini-pro'})
                    });
                    const data = await resp.json();
                    output.innerHTML += '<div>🤖 ' + data.response + '</div><br>';
                } catch (err) {
                    output.innerHTML += '<div>❌ ' + err + '</div><br>';
                }
            }
        });
    </script>
</body>
</html>
EOF

# Přidat route pro terminál do webapp.py
python3 <<'PYEOF'
with open("webapp.py", "r") as f:
    content = f.read()

# Najít @app.get("/") a přidat /terminal
if '@app.get("/terminal")' not in content:
    terminal_route = '''
@app.get("/terminal")
async def terminal_page():
    return FileResponse("static/terminal.html")
'''
    # Přidat před health endpoint
    content = content.replace('@app.get("/health")', terminal_route + '@app.get("/health")')

with open("webapp.py", "w") as f:
    f.write(content)

print("✅ /terminal route přidán")
PYEOF

echo "✅ Webapp rozšířena: /execute, /terminal"
echo "📝 Restartuj webapp: pkill -f 'python3 webapp.py' && nohup python3 webapp.py > /tmp/cb26-webapp.log 2>&1 &"
echo "🌐 Otevři: http://localhost:8080/terminal"
