#!/bin/bash

#############################################
# AI Dev System - Web Service Manager
# Web 服務管理（啟動/停止/重啟/狀態）
#############################################

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WEB_PID_FILE="$HOME/.ai-dev-logs/web-server.pid"
NGROK_PID_FILE="$HOME/.ai-dev-logs/ngrok.pid"
DEFAULT_PORT=8000

# 顏色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

get_web_status() {
    if [ -f "$WEB_PID_FILE" ]; then
        WEB_PID=$(cat "$WEB_PID_FILE")
        if kill -0 $WEB_PID 2>/dev/null; then
            return 0  # 運行中
        fi
    fi
    return 1  # 未運行
}

get_ngrok_status() {
    if [ -f "$NGROK_PID_FILE" ]; then
        NGROK_PID=$(cat "$NGROK_PID_FILE")
        if kill -0 $NGROK_PID 2>/dev/null; then
            return 0  # 運行中
        fi
    fi
    return 1  # 未運行
}

start_service() {
    if get_web_status; then
        echo -e "${YELLOW}Web 服務已在運行中${NC}"
        return 1
    fi
    
    echo -e "${GREEN}啟動 Web 服務...${NC}"
    bash "$SCRIPT_DIR/start-web.sh" "$@" --daemon
}

stop_service() {
    local stopped=false
    
    if get_web_status; then
        WEB_PID=$(cat "$WEB_PID_FILE")
        echo -e "${YELLOW}停止 Web Server (PID: $WEB_PID)...${NC}"
        kill $WEB_PID 2>/dev/null
        rm -f "$WEB_PID_FILE"
        rm -f "$HOME/.ai-dev-logs/web-server-port"  # 清理端口文件
        stopped=true
    fi
    
    if get_ngrok_status; then
        NGROK_PID=$(cat "$NGROK_PID_FILE")
        echo -e "${YELLOW}停止 Ngrok (PID: $NGROK_PID)...${NC}"
        kill $NGROK_PID 2>/dev/null
        rm -f "$NGROK_PID_FILE"
        stopped=true
    fi
    
    if [ "$stopped" = true ]; then
        echo -e "${GREEN}✓ 服務已停止${NC}"
    else
        echo -e "${YELLOW}服務未運行${NC}"
    fi
}

restart_service() {
    echo -e "${BLUE}重新啟動服務...${NC}"
    stop_service
    sleep 2
    start_service "$@"
}

show_status() {
    echo -e "${BLUE}=========================================${NC}"
    echo -e "${BLUE}  Web Dashboard 狀態${NC}"
    echo -e "${BLUE}=========================================${NC}"
    echo ""
    
    # 獲取當前運行的端口
    local current_port=$DEFAULT_PORT
    if [ -f "$HOME/.ai-dev-logs/web-server-port" ]; then
        current_port=$(cat "$HOME/.ai-dev-logs/web-server-port")
    fi
    
    if get_web_status; then
        WEB_PID=$(cat "$WEB_PID_FILE")
        echo -e "  Web Server:  ${GREEN}運行中${NC} (PID: $WEB_PID)"
        echo -e "  本地訪問:    ${GREEN}http://localhost:${current_port}${NC}"
    else
        echo -e "  Web Server:  ${RED}未運行${NC}"
    fi
    
    echo ""
    
    if get_ngrok_status; then
        NGROK_PID=$(cat "$NGROK_PID_FILE")
        echo -e "  Ngrok:       ${GREEN}運行中${NC} (PID: $NGROK_PID)"
        
        # 嘗試取得 ngrok URL
        NGROK_URL=$(curl -s http://localhost:4040/api/tunnels 2>/dev/null | grep -o '"public_url":"https://[^"]*' | head -1 | cut -d'"' -f4)
        if [ -n "$NGROK_URL" ]; then
            echo -e "  遠程訪問:    ${GREEN}${NGROK_URL}${NC}"
        else
            echo -e "  Ngrok URL:   檢查 http://localhost:4040"
        fi
    else
        echo -e "  Ngrok:       ${YELLOW}未啟用${NC}"
        echo -e "               使用 --ngrok 參數啟動遠程訪問"
    fi
    
    echo ""
}

show_help() {
    cat <<EOF
使用方式: $0 <command> [options]

Commands:
    start [--port PORT] [--ngrok]    啟動 Web Dashboard
                                     --port 或 -p: 指定端口 (預設: $DEFAULT_PORT)
                                     --ngrok 或 -n: 同時啟動 ngrok 遠程訪問
    stop                             停止所有服務
    restart [--port PORT] [--ngrok]  重新啟動服務
    status                           查看服務狀態
    logs [type]                      查看日誌
                                     type: web (預設), ngrok
    help                             顯示此說明

範例:
    $0 start                         # 啟動（預設端口 $DEFAULT_PORT）
    $0 start --port 9000             # 啟動在端口 9000
    $0 start --port 8080 --ngrok     # 啟動在端口 8080 + ngrok
    $0 status                        # 查看狀態
    $0 logs web                      # 查看 web server 日誌
    $0 stop                          # 停止服務

訪問:
    本地:    http://localhost:PORT (PORT 為指定的端口)
    API文檔: http://localhost:PORT/docs
    Ngrok:   需先啟動 ngrok（使用 --ngrok 參數）
EOF
}

view_logs() {
    local log_type=${1:-web}
    
    case "$log_type" in
        web)
            LOG_FILE="$HOME/.ai-dev-logs/web-server.log"
            ;;
        ngrok)
            LOG_FILE="$HOME/.ai-dev-logs/ngrok.log"
            ;;
        *)
            echo -e "${RED}未知的日誌類型: $log_type${NC}"
            echo "可用類型: web, ngrok"
            exit 1
            ;;
    esac
    
    if [ -f "$LOG_FILE" ]; then
        echo -e "${BLUE}查看日誌: $LOG_FILE${NC}"
        echo -e "${BLUE}(按 Ctrl+C 退出)${NC}"
        echo ""
        tail -f "$LOG_FILE"
    else
        echo -e "${YELLOW}日誌檔案不存在: $LOG_FILE${NC}"
    fi
}

# 主程式
case "${1:-help}" in
    start)
        shift
        start_service "$@"
        ;;
    stop)
        stop_service
        ;;
    restart)
        shift
        restart_service "$@"
        ;;
    status)
        show_status
        ;;
    logs)
        view_logs "$2"
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        echo -e "${RED}未知的命令: $1${NC}"
        echo ""
        show_help
        exit 1
        ;;
esac
