#!/bin/bash
# BTC Bottom Panel 管理脚本

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="$SCRIPT_DIR/server.pid"
LOG_FILE="$SCRIPT_DIR/server.log"

check_running() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            return 0
        fi
    fi
    return 1
}

case "${1:-status}" in
    start)
        if check_running; then
            echo "Server already running (PID: $(cat $PID_FILE))"
            echo "Dashboard: http://localhost:8765/frontend/index.html"
            exit 0
        fi
        cd "$SCRIPT_DIR"
        setsid python3 -c "
import json
from pathlib import Path
from http.server import HTTPServer, SimpleHTTPRequestHandler

ROOT = Path('.')
DATA_FILE = ROOT / 'data' / 'indicators.json'

class Handler(SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(ROOT), **kwargs)
    def log_message(self, format, *args):
        pass
    def do_OPTIONS(self):
        self.send_response(204)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
    def do_GET(self):
        if self.path == '/api/data' or self.path.startswith('/api/data?'):
            try:
                data = json.loads(DATA_FILE.read_text(encoding='utf-8'))
                body = json.dumps(data, ensure_ascii=False).encode('utf-8')
                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Content-Length', str(len(body)))
                self.end_headers()
                self.wfile.write(body)
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({'error': str(e)}).encode())
        else:
            super().do_GET()
    def do_POST(self):
        if self.path == '/api/refresh':
            import subprocess, sys
            fetcher = ROOT / 'backend' / 'fetch_data.py'
            result = subprocess.run([sys.executable, str(fetcher)], capture_output=True, text=True)
            if result.returncode == 0 and DATA_FILE.exists():
                self.do_GET()
            else:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({'error': 'Refresh failed'}).encode())
        else:
            self.send_error(404)

server = HTTPServer(('0.0.0.0', 8765), Handler)
with open('$LOG_FILE', 'w') as f:
    f.write('Server started at http://0.0.0.0:8765\n')
    f.write('Dashboard: http://0.0.0.0:8765/frontend/index.html\n')
    f.write('API: http://0.0.0.0:8765/api/data\n')
server.serve_forever()
" > /dev/null 2>&1 &
echo $! > "$PID_FILE"
        sleep 1
        echo "Server started (PID: $(cat $PID_FILE))"
        echo "Dashboard: http://localhost:8765/frontend/index.html"
        ;;
    stop)
        if check_running; then
            kill -9 $(cat "$PID_FILE")
            rm -f "$PID_FILE"
            echo "Server stopped"
        else
            echo "Server not running"
        fi
        ;;
    restart)
        $0 stop
        sleep 1
        $0 start
        ;;
    status)
        if check_running; then
            echo "Server running (PID: $(cat $PID_FILE))"
            echo "Dashboard: http://localhost:8765/frontend/index.html"
            echo "API: http://localhost:8765/api/data"
        else
            echo "Server not running"
        fi
        ;;
    fetch)
        cd "$SCRIPT_DIR"
        echo "Fetching latest data..."
        python3 backend/fetch_data.py
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status|fetch}"
        exit 1
        ;;
esac
