#!/usr/bin/env bash
# OpenClaw 遠端修復服務啟動器
# 雙擊啟動後，手機連同 WiFi 就能用瀏覽器修復

cd "$(dirname "$0")"
python3 -c "
import http.server, json, subprocess, socket, os, signal, sys, threading, time

PORT = 9876
PID_FILE = os.path.expanduser('~/.openclaw-fix-server.pid')

# 取得 IP
def get_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except:
        return '127.0.0.1'

IP = get_ip()
HTML = '''<!DOCTYPE html>
<html lang=\"zh-Hant\">
<head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,user-scalable=no\">
<title>OpenClaw 修復</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{background:#1a1a2e;color:#eee;font-family:-apple-system,sans-serif;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:20px;text-align:center}
h1{font-size:26px;margin-bottom:8px;color:#e94560}
p{font-size:14px;color:#888;margin-bottom:30px}
.btn{display:inline-block;padding:18px 48px;font-size:22px;font-weight:bold;color:#fff;background:#e94560;border:none;border-radius:16px;cursor:pointer;touch-action:manipulation}
.btn:active{transform:scale(.95)}
.btn:disabled{background:#555;cursor:not-allowed}
.st{margin-top:24px;padding:14px 20px;border-radius:12px;font-size:14px;min-height:48px;width:100%;max-width:360px}
.idle{background:#16213e;border:1px solid #0f3460;color:#888}
.ok{background:#1a4332;border:1px solid #2d6a4f;color:#95d5b2}
.err{background:#4a1525;border:1px solid #a4133c;color:#ffb3b3}
.load{background:#16213e;border:1px solid #e94560;color:#e94560}
</style></head>
<body>
<h1>🔧 OpenClaw 修復</h1>
<p>''' + IP + ''' : 9876</p>
<button class=\"btn\" id=\"fixBtn\">🔨 開始修復</button>
<div class=\"st idle\" id=\"status\">點擊按鈕遠端修復</div>
<script>
const btn=document.getElementById('fixBtn');
const st=document.getElementById('status');
btn.onclick=async()=>{
  btn.disabled=true;
  st.className='st load';st.textContent='⏳ 正在修復...';
  try{
    const r=await fetch('/fix',{method:'POST'});
    const d=await r.json();
    if(d.ok){st.className='st ok';st.textContent='✅ 修復完成！請回 Telegram 發送 /new'}
    else{st.className='st err';st.textContent='❌ '+d.error}
  }catch(e){st.className='st err';st.textContent='❌ 無法連線到 Mac'}
  btn.disabled=false;
};
</script></body></html>'''

class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.end_headers()
            self.wfile.write(HTML.encode('utf-8'))
        else:
            self.send_error(404)

    def do_POST(self):
        if self.path == '/fix':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            # 執行修復（背景執行）
            def fix():
                subprocess.run(['pkill', '-f', 'openclaw'], capture_output=True)
                time.sleep(3)
                subprocess.run(['openclaw', 'gateway', 'restart', '--force'],
                             capture_output=True)
            threading.Thread(target=fix, daemon=True).start()
            
            result = {'ok': True, 'message': '修復指令已發送，約10秒後恢復'}
            self.wfile.write(json.dumps(result).encode('utf-8'))
        else:
            self.send_error(404)

    def log_message(self, format, *args):
        pass  # 不輸出到終端機

# 寫 PID
with open(PID_FILE, 'w') as f:
    f.write(str(os.getpid()))

print('=== OpenClaw 遠端修復服務 ===')
print(f'📱 手機瀏覽器打開：http://{IP}:{PORT}')
print(f'按 Ctrl+C 停止服務')
print()

server = http.server.HTTPServer(('0.0.0.0', PORT), Handler)
try:
    server.serve_forever()
except KeyboardInterrupt:
    server.shutdown()
    os.unlink(PID_FILE)
    print('服務已停止')
"