#!/bin/bash
# ============================================================
# 问题排查助手 - Linux 部署脚本
# 运行方式: bash deploy.sh
#
# 说明：从 skill/code/web/ 复制源代码到部署目录
#       deploy/web/ 目录已删除，统一使用单一数据源
# ============================================================

set -e

echo "=================================================="
echo "  问题排查助手 部署脚本"
echo "=================================================="

# 配置
DEPLOY_DIR="/opt/troubleshoot"
WEB_PORT=8088
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "[1/5] 安装 Python 依赖..."
pip3 install -r "$PROJECT_ROOT/skill/code/requirements.txt" -q 2>/dev/null || \
    pip install -r "$PROJECT_ROOT/skill/code/requirements.txt" -q

echo "[2/5] 创建部署目录..."
sudo mkdir -p $DEPLOY_DIR
sudo mkdir -p $DEPLOY_DIR/问题记录

echo "[3/5] 复制 Web 服务（从 skill/code/web/）..."
# 从统一源目录 skill/code/web/ 复制
sudo cp -r "$PROJECT_ROOT/skill/code/web" "$DEPLOY_DIR/"

echo "[4/5] 复制问题记录和搜索索引..."
sudo cp -r "$SCRIPT_DIR/问题记录"/* "$DEPLOY_DIR/问题记录/" 2>/dev/null || true
sudo cp "$PROJECT_ROOT/Docs/搜索索引.json" "$DEPLOY_DIR/" 2>/dev/null || true
sudo cp "$PROJECT_ROOT/skill/code/build_index.py" "$DEPLOY_DIR/"

echo "[5/5] 配置权限和 systemd 服务..."
sudo chown -R $USER:$USER $DEPLOY_DIR

sudo tee /etc/systemd/system/troubleshoot.service > /dev/null << EOF
[Unit]
Description=问题排查助手 Web 服务
After=network.target

[Service]
Type=simple
User=$USER
WorkingDirectory=$DEPLOY_DIR/web
ExecStart=/usr/bin/python3 $DEPLOY_DIR/web/server.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable troubleshoot.service
sudo systemctl start troubleshoot.service

echo ""
echo "=================================================="
echo "  部署完成！"
echo "=================================================="
echo "  访问地址: http://$(hostname -I | awk '{print $1}'):$WEB_PORT"
echo "  查看状态: sudo systemctl status troubleshoot"
echo "  查看日志: sudo journalctl -u troubleshoot -f"
echo "  重启服务: sudo systemctl restart troubleshoot"
echo "=================================================="