#!/bin/bash
#================================================================================
# GEO-SEO Optimizer - 环境初始化脚本
# 用途: 恢复上下文、验证环境、推荐任务
# 作者: KIMI-2.5 持续开发系统
# 版本: 1.0.0
#================================================================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 项目配置
PROJECT_NAME="GEO-SEO Optimizer"
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TASK_FILE="$PROJECT_ROOT/task.json"
PROGRESS_FILE="$PROJECT_ROOT/progress.txt"
CLOUD_FILE="$PROJECT_ROOT/cloud.md"

echo ""
echo -e "${CYAN}╔════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║               ${PROJECT_NAME} - 初始化系统                 ║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════════════════════════════╝${NC}"
echo ""

#================================================================================
# Step 1: 验证核心文件
#================================================================================
echo -e "${BLUE}[1/6]${NC} 验证核心文件..."

for file in "$TASK_FILE" "$PROGRESS_FILE" "$CLOUD_FILE"; do
    if [[ ! -f "$file" ]]; then
        echo -e "${RED}✗ 缺失文件: $file${NC}"
        exit 1
    fi
done
echo -e "${GREEN}✓${NC} task.json - OK"
echo -e "${GREEN}✓${NC} progress.txt - OK"
echo -e "${GREEN}✓${NC} cloud.md - OK"

#================================================================================
# Step 2: 检查 Python 环境
#================================================================================
echo ""
echo -e "${BLUE}[2/6]${NC} 检查 Python 环境..."

if ! command -v python3 &> /dev/null; then
    echo -e "${RED}✗ Python3 未安装${NC}"
    exit 1
fi

PYTHON_VERSION=$(python3 --version 2>&1 | grep -oE '[0-9]+\.[0-9]+' | head -1)
REQUIRED_VERSION="3.11"

if [[ "$(printf '%s\n' "$REQUIRED_VERSION" "$PYTHON_VERSION" | sort -V | head -n1)" != "$REQUIRED_VERSION" ]]; then
    echo -e "${RED}✗ Python 版本 $PYTHON_VERSION 过低，需要 $REQUIRED_VERSION+${NC}"
    exit 1
fi
echo -e "${GREEN}✓${NC} Python $PYTHON_VERSION"

#================================================================================
# Step 3: 安装/验证依赖
#================================================================================
echo ""
echo -e "${BLUE}[3/6]${NC} 验证项目依赖..."

if [[ -f "$PROJECT_ROOT/pyproject.toml" ]]; then
    # 检查关键依赖
    REQUIRED_PACKAGES=("pydantic" "typer" "rich" "aiosqlite")
    MISSING_PACKAGES=()

    for pkg in "${REQUIRED_PACKAGES[@]}"; do
        if ! python3 -c "import $pkg" 2>/dev/null; then
            MISSING_PACKAGES+=("$pkg")
        fi
    done

    if [[ ${#MISSING_PACKAGES[@]} -gt 0 ]]; then
        echo -e "${YELLOW}! 缺失依赖: ${MISSING_PACKAGES[*]}${NC}"
        echo -e "${BLUE}  正在安装...${NC}"
        cd "$PROJECT_ROOT"
        pip install -e ".[dev]" --quiet 2>/dev/null || pip install pydantic typer rich aiosqlite jinja2 pyyaml pytest pytest-asyncio mypy --quiet
    fi
    echo -e "${GREEN}✓${NC} 依赖已安装"
else
    echo -e "${YELLOW}! pyproject.toml 不存在，跳过依赖检查${NC}"
fi

#================================================================================
# Step 4: 加载任务清单
#================================================================================
echo ""
echo -e "${BLUE}[4/6]${NC} 加载任务清单..."

python3 << EOF
import json
import sys

try:
    with open("$TASK_FILE", "r") as f:
        data = json.load(f)

    total = data.get("total_count", 0)
    completed = data.get("completed_count", 0)
    active = data.get("active_task")

    pending = [t for t in data["tasks"] if t["status"] == "pending"]
    in_progress = [t for t in data["tasks"] if t["status"] == "in_progress"]
    blocked = [t for t in data["tasks"] if t["status"] == "blocked"]

    progress_pct = (completed / total * 100) if total > 0 else 0

    print(f"总任务: {total}")
    print(f"已完成: {completed} ({progress_pct:.1f}%)")
    print(f"进行中: {len(in_progress)}")
    print(f"待处理: {len(pending)}")
    print(f"阻塞中: {len(blocked)}")

    if active:
        print(f"\n活跃任务: {active}")

except Exception as e:
    print(f"错误: {e}", file=sys.stderr)
    sys.exit(1)
EOF

#================================================================================
# Step 5: 显示最近进度
#================================================================================
echo ""
echo -e "${BLUE}[5/6]${NC} 最近进度..."
echo -e "${CYAN}────────────────────────────────────────────────────────────────${NC}"

if [[ -f "$PROGRESS_FILE" ]]; then
    # 显示最后 15 行，但只显示完整的会话记录
    tail -20 "$PROGRESS_FILE" | head -15
fi

echo -e "${CYAN}────────────────────────────────────────────────────────────────${NC}"

#================================================================================
# Step 6: 推荐下一个任务
#================================================================================
echo ""
echo -e "${BLUE}[6/6]${NC} 任务推荐..."
echo ""

python3 << 'PYEOF'
import json
from datetime import datetime

def get_next_task():
    with open("task.json", "r") as f:
        data = json.load(f)

    tasks = data["tasks"]

    # 检查是否有进行中的任务
    active = data.get("active_task")
    if active:
        task = next((t for t in tasks if t["id"] == active), None)
        if task:
            return {
                "type": "active",
                "task": task
            }

    # 找 pending 且依赖满足的任务
    for task in tasks:
        if task["status"] != "pending":
            continue

        deps = task.get("dependencies", [])
        deps_satisfied = all(
            any(t2["id"] == d and t2["status"] == "completed" for t2 in tasks)
            for d in deps
        )

        if deps_satisfied:
            return {
                "type": "next",
                "task": task
            }

    # 所有任务完成
    pending_count = len([t for t in tasks if t["status"] == "pending"])
    if pending_count == 0:
        return {"type": "done"}

    return {"type": "blocked"}

result = get_next_task()

if result["type"] == "done":
    print("🎉 所有任务已完成！")
elif result["type"] == "blocked":
    print("⚠️  所有待处理任务都有未满足的依赖")
    print("   请检查 task.json 中的阻塞任务")
elif result["type"] == "active":
    task = result["task"]
    print(f"▶️  当前活跃任务: {task['id']}")
    print(f"   标题: {task['title']}")
    print(f"   阶段: {task['phase']}")
    print(f"   预计: {task['estimated_minutes']} 分钟")
    print("")
    print("   验收标准:")
    for i, ac in enumerate(task['acceptance_criteria'], 1):
        print(f"     {i}. {ac}")
elif result["type"] == "next":
    task = result["task"]
    print(f"📋 推荐任务: {task['id']}")
    print(f"   标题: {task['title']}")
    print(f"   阶段: {task['phase']}")
    print(f"   预计: {task['estimated_minutes']} 分钟")
    print("")
    print("   验收标准:")
    for i, ac in enumerate(task['acceptance_criteria'], 1):
        print(f"     {i}. {ac}")
    print("")
    print(f"   执行以下命令领取任务:")
    print(f"   python3 -c \"import json; data=json.load(open('task.json')); [t.update({{'status':'in_progress','started_at':'{datetime.now().isoformat()}'}}) if t['id']=='{task['id']}' else None for t in data['tasks']]); data['active_task']='{task['id']}'; json.dump(data,open('task.json','w'),indent=2)\" ")

PYEOF

echo ""

#================================================================================
# 系统状态摘要
#================================================================================
echo -e "${CYAN}════════════════════════════════════════════════════════════════${NC}"
echo -e "                     ${GREEN}初始化完成${NC}"
echo -e "${CYAN}════════════════════════════════════════════════════════════════${NC}"
echo ""
echo "下一步操作:"
echo "  1. 阅读 cloud.md 了解工作流程"
echo "  2. 按上述命令领取推荐任务"
echo "  3. 开始编码 (Step 3: CODE)"
echo ""
echo -e "文档: ${YELLOW}cat cloud.md${NC}"
echo -e "进度: ${YELLOW}cat progress.txt${NC}"
echo -e "任务: ${YELLOW}cat task.json${NC} | python3 -m json.tool"
echo ""
