#!/bin/bash

# 即梦 Free API 部署脚本
# 使用方法: ./deploy.sh [start|stop|restart|status|logs|build] [options]

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查依赖
check_dependencies() {
    log_info "检查系统依赖..."
    
    if ! command -v docker &> /dev/null; then
        log_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi
    
    log_success "依赖检查通过"
}

# 构建镜像
build_images() {
    log_info "构建 Docker 镜像..."
    docker-compose build --no-cache
    log_success "镜像构建完成"
}

# 启动服务
start_service() {
    log_info "启动即梦 Free API 服务..."
    docker-compose up -d
    log_success "服务启动完成"
}

# 停止服务
stop_service() {
    log_info "停止服务..."
    docker-compose down
    log_success "服务已停止"
}

# 重启服务
restart_service() {
    log_info "重启服务..."
    docker-compose restart
    log_success "服务重启完成"
}

# 查看服务状态
check_status() {
    log_info "检查服务状态..."
    
    echo "=== Docker 容器状态 ==="
    docker-compose ps
    
    echo
    echo "=== 服务健康检查 ==="
    
    # 检查 API 服务
    CONTAINER_PORT=$(docker-compose port jimeng-free-api 3302 2>/dev/null | cut -d: -f2)
    if [ -n "$CONTAINER_PORT" ]; then
        if curl -s http://localhost:$CONTAINER_PORT/ping > /dev/null 2>&1; then
            log_success "API 服务正常运行 (:$CONTAINER_PORT)"
            
            # 检查服务器心跳
            if curl -s http://localhost:$CONTAINER_PORT/api/servers/current > /dev/null 2>&1; then
                echo
                echo "=== 当前服务器信息 ==="
                curl -s http://localhost:$CONTAINER_PORT/api/servers/current | jq '.data' 2>/dev/null || echo "需要安装 jq 来格式化 JSON 输出"
            fi
        else
            log_error "API 服务无法访问"
        fi
    else
        log_warning "API 服务端口未暴露或服务未运行"
    fi
}

# 查看日志
view_logs() {
    local follow=${1:-""}
    
    if [ "$follow" = "-f" ] || [ "$follow" = "--follow" ]; then
        log_info "实时查看服务日志..."
        docker-compose logs -f --tail=100
    else
        log_info "查看服务日志..."
        docker-compose logs --tail=100
    fi
}

# 显示帮助信息
show_help() {
    echo "即梦 Free API 部署脚本"
    echo
    echo "使用方法:"
    echo "  $0 <command> [options]"
    echo
    echo "命令:"
    echo "  start        启动服务"
    echo "  stop         停止服务"
    echo "  restart      重启服务"
    echo "  status       查看服务状态"
    echo "  logs [-f]    查看日志 (-f 实时跟踪)"
    echo "  build        仅构建镜像"
    echo "  help         显示此帮助信息"
    echo
    echo "示例:"
    echo "  $0 start                  # 启动服务"
    echo "  $0 logs -f               # 实时查看日志"
    echo "  $0 status                # 检查服务状态"
    echo
    echo "环境变量配置:"
    echo "  请在 docker-compose.yml 中或系统环境变量中配置:"
    echo "  - MONGODB_URL: MongoDB 连接地址"
    echo "  - TOS_ACCESS_KEY_ID: TOS 访问密钥 ID"
    echo "  - TOS_ACCESS_KEY_SECRET: TOS 访问密钥"
    echo "  - TOS_BUCKET_NAME: TOS 存储桶名称"
    echo "  - SERVICE_ID: 服务器唯一标识"
}

# 主函数
main() {
    local command="$1"
    
    case "$command" in
        start)
            check_dependencies
            start_service
            sleep 5
            check_status
            ;;
        stop)
            stop_service
            ;;
        restart)
            restart_service
            sleep 5
            check_status
            ;;
        status)
            check_status
            ;;
        logs)
            view_logs "$2"
            ;;
        build)
            check_dependencies
            build_images
            ;;
        help|--help|-h)
            show_help
            ;;
        "")
            log_error "请指定命令"
            show_help
            exit 1
            ;;
        *)
            log_error "未知命令: $command"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"