#!/bin/bash
set -e

echo "=========================================="
echo "  sanguo_vnpy Docker 容器启动中..."
echo "=========================================="

# 安装回测服务必需依赖（容器重启后pip包会丢失，启动时自动重装）
echo "正在安装回测服务依赖..."
pip3 install vnpy_ctastrategy vnpy_sqlite --quiet 2>&1 | tail -3
echo "✅ 依赖安装完成"

# SSH服务 - 修复端口绑定问题
sudo sed -i 's/#Port 22/Port 22/' /etc/ssh/sshd_config
sudo /usr/sbin/sshd -D &

# Jupyter Lab
jupyter lab --ip=0.0.0.0 --port=8888 --no-browser \
    --NotebookApp.token='sanguo123' \
    --NotebookApp.password='' \
    --NotebookApp.allow_origin='*' &

# 自动化回测服务（uvicorn包方式启动）
mkdir -p /app/logs
# 目录名含连字符不能做Python包，需要用下划线版本的目录
if [ -d /app/scripts/backtest_service ]; then
    BT_PKG_DIR=/app/scripts
elif [ -d /app/scripts/backtest-service ]; then
    # 旧镜像目录名含连字符，创建符号链接
    ln -sf /app/scripts/backtest-service /app/scripts/backtest_service
    BT_PKG_DIR=/app/scripts
else
    BT_PKG_DIR=""
fi

if [ -n "$BT_PKG_DIR" ]; then
    PYTHONPATH=$BT_PKG_DIR uvicorn backtest_service.main:app \
        --host 0.0.0.0 --port 8088 \
        >> /app/logs/backtest-service.log 2>&1 &
    BT_PID=$!
    echo "回测服务已启动 (PID=$BT_PID, 端口8088)"
fi

# code-server
code-server &

sleep 5

# 健康检查
if curl -sf http://localhost:8088/api/backtest/health > /dev/null 2>&1; then
    echo "✅ 回测服务健康检查通过"
else
    echo "⚠️  回测服务尚未就绪，检查日志: /app/logs/backtest-service.log"
fi

echo ""
echo "✅ sanguo_vnpy 环境启动成功！"
echo ""
echo "访问地址："
echo "  Jupyter Lab:   http://localhost:8888 (token: sanguo123)"
echo "  回测服务:      http://localhost:8088/api/backtest/health"
echo "  回测API文档:   http://localhost:8088/docs"
echo "  SSH:           ssh -p 2222 vnpy@localhost (password: sanguo123)"
echo ""
echo "数据目录: /app/data"
echo "策略目录: /app/strategies"
echo ""

tail -f /dev/null
