#!/usr/bin/env bash
# 清理孤儿任务 — 删除不属于任何现有项目的任务记录
# 用法：bash scripts/cleanup_orphan_tasks.sh
#
# 数据库路径：Windows %APPDATA%/top.1216.devflow/devflow-dev.db (dev) 或 devflow.db (release)

set -euo pipefail

# 自动定位数据库文件
DB_PATH="${1:-}"

if [ -z "$DB_PATH" ]; then
    # 尝试常见路径
    for candidate in \
        "$APPDATA/top.1216.devflow/devflow-dev.db" \
        "$LOCALAPPDATA/top.1216.devflow/devflow-dev.db" \
        "$HOME/AppData/Roaming/top.1216.devflow/devflow-dev.db"; do
        if [ -f "$candidate" ]; then
            DB_PATH="$candidate"
            break
        fi
    done
fi

if [ -z "$DB_PATH" ] || [ ! -f "$DB_PATH" ]; then
    echo "❌ 未找到数据库文件，请手动指定路径："
    echo "   bash scripts/cleanup_orphan_tasks.sh <db_path>"
    echo ""
    echo "   通常位于: %APPDATA%\\top.1216.devflow\\devflow-dev.db"
    exit 1
fi

echo "📍 数据库: $DB_PATH"
echo ""

# 先查看孤儿任务
echo "=== 孤儿任务列表（project_id 不在 projects 表中）==="
sqlite3 "$DB_PATH" "
    SELECT t.id, t.title, t.project_id
    FROM tasks t
    LEFT JOIN projects p ON t.project_id = p.id
    WHERE p.id IS NULL
    ORDER BY t.project_id, t.created_at;
"
echo ""

# 统计数量
COUNT=$(sqlite3 "$DB_PATH" "
    SELECT COUNT(*)
    FROM tasks t
    LEFT JOIN projects p ON t.project_id = p.id
    WHERE p.id IS NULL;
")

echo "📊 孤儿任务总数: $COUNT"
echo ""

if [ "$COUNT" -eq 0 ]; then
    echo "✅ 无孤儿任务，无需清理。"
    exit 0
fi

read -p "确认删除以上 $COUNT 条孤儿任务？(y/N) " confirm
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
    echo "已取消。"
    exit 0
fi

# 执行删除
sqlite3 "$DB_PATH" "
    DELETE FROM tasks
    WHERE project_id NOT IN (SELECT id FROM projects);
"

echo "✅ 已删除 $COUNT 条孤儿任务。"
