#!/bin/bash

# Stock Tool - PERDAS 增强版初始化脚本
# 用途：启动或重启开发环境

set -e  # 遇到错误立即退出

echo "🚀 启动 Stock Tool 开发环境..."
echo ""

# 检查 Go 是否安装
if ! command -v go &> /dev/null; then
    echo "❌ 错误: 未安装 Go"
    echo "请先安装 Go 1.21+: https://go.dev/dl/"
    exit 1
fi

# 检查项目目录
if [ ! -f "stock-tool-simple" ]; then
    echo "⚠️  警告: 未找到 stock-tool-simple 可执行文件"
    echo "正在尝试编译..."
    if [ -f "main_simple.go" ]; then
        go build -o stock-tool-simple main_simple.go
    else
        echo "❌ 错误: 找不到 main_simple.go"
        exit 1
    fi
fi

# 检查数据库文件
if [ ! -f "stock.db" ]; then
    echo "📝 初始化数据库..."
    sqlite3 stock.db "CREATE TABLE IF NOT EXISTS stocks (id INTEGER PRIMARY KEY AUTOINCREMENT, symbol TEXT UNIQUE, name TEXT, current_price REAL, change REAL, change_percent REAL, market_cap TEXT, pe_ratio REAL, roe REAL, debt_ratio REAL, update_time TEXT);"
    sqlite3 stock.db "CREATE TABLE IF NOT EXISTS klines (id INTEGER PRIMARY KEY AUTOINCREMENT, symbol TEXT, date TEXT, open REAL, high REAL, low REAL, close REAL, volume INTEGER, FOREIGN KEY(symbol) REFERENCES stocks(symbol));"
    sqlite3 stock.db "CREATE TABLE IF NOT EXISTS indicators (id INTEGER PRIMARY KEY AUTOINCREMENT, symbol TEXT, date TEXT, rsi REAL, macd REAL, macd_signal REAL, ma5 REAL, ma10 REAL, ma20 REAL, update_time TEXT, FOREIGN KEY(symbol) REFERENCES stocks(symbol));"
    sqlite3 stock.db "CREATE TABLE IF NOT EXISTS financials (id INTEGER PRIMARY KEY AUTOINCREMENT, symbol TEXT UNIQUE, revenue REAL, profit REAL, roe REAL, debt_to_equity REAL, update_time TEXT);"
fi

# 检查是否已有进程在运行
if pgrep -f "stock-tool-simple" > /dev/null; then
    echo "⚠️  检测到已有进程在运行"
    echo "正在停止旧进程..."
    pkill -f "stock-tool-simple"
    sleep 2
fi

# 启动服务器
echo "🌐 启动服务器..."
echo "   地址: http://localhost:8080"
echo ""

# 创建日志目录
mkdir -p logs

# 后台运行
nohup ./stock-tool-simple > logs/server.log 2>&1 &
SERVER_PID=$!

# 等待服务器启动
echo "⏳ 等待服务器启动..."
sleep 3

# 检查服务器是否成功启动
if pgrep -f "stock-tool-simple" > /dev/null; then
    echo ""
    echo "✅ 服务器启动成功!"
    echo ""
    echo "📋 服务器信息:"
    echo "   - PID: $SERVER_PID"
    echo "   - URL: http://localhost:8080"
    echo "   - 日志: logs/server.log"
    echo ""
    echo "📊 当前状态:"
    echo "   - 仓库: http://gitea.xieyao.vip/xieyao/stock-tool"
    echo "   - 功能: $(jq '.summary.completed' feature_list.json)/$(jq '.summary.total' feature_list.json) 完成"
    echo ""
    echo "💡 下一步:"
    echo "   1. 在浏览器访问 http://localhost:8080"
    echo "   2. 运行 ./scripts/health-check.sh 进行健康检查"
    echo "   3. 查看 feature_list.json 了解功能清单"
    echo ""
    echo "💾 保存 PID 到文件"
    echo $SERVER_PID > .server.pid

    # 保存到内存
    echo "SERVER_PID=$SERVER_PID" >> .env 2>/dev/null || echo "SERVER_PID=$SERVER_PID" > .env

else
    echo ""
    echo "❌ 服务器启动失败"
    echo "查看日志: cat logs/server.log"
    exit 1
fi
