#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
直接写入 tracker.db 的脚本
"""

import sqlite3
from datetime import datetime

DB_PATH = "tracker.db"


def init_database():
    """初始化所有 Phase 4 和 Phase 6 的任务数据"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    # 清空现有数据
    cursor.execute("DELETE FROM logs")
    cursor.execute("DELETE FROM tasks")
    cursor.execute("DELETE FROM milestones")

    print("=" * 60)
    print("初始化 xiaoxia-saas 项目数据到 tracker.db")
    print("=" * 60)

    # ========== Phase 4: SAAS 产品化 ==========
    print("\n[Phase 4] 初始化任务...")

    # Milestone 1: 认证与账号体系
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("认证与账号体系", "Phase 4", "2026-06-10", "2026-06-17", "completed", "JWT 登录、注册、密码管理"),
    )
    milestone1_id = cursor.lastrowid

    auth_tasks = [
        ("JWT 工具类实现", "sign/verify/refresh Token 功能", "completed", "high"),
        ("bcrypt 密码哈希工具", "密码加密存储", "completed", "high"),
        ("Redis Session 存储", "refresh_token 存储和管理", "completed", "high"),
        ("邮件服务封装", "SMTP + 邮件模板", "completed", "medium"),
        ("User 实体扩展", "新增 password_hash/email_verified 等字段", "completed", "high"),
        ("注册 API", "邮箱 + 密码注册", "completed", "high"),
        ("登录 API", "JWT 签发 access_token", "completed", "high"),
        ("登出 API", "撤销 refresh_token", "completed", "high"),
        ("刷新 Token API", "用 refresh_token 换取新 access_token", "completed", "high"),
        ("密码重置流程", "忘记密码 + 邮件重置", "completed", "medium"),
    ]

    for name, desc, status, priority in auth_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 4", "认证与账号体系", priority, datetime.now().isoformat()),
        )

    # Milestone 2: 多租户权限体系
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("多租户权限体系", "Phase 4", "2026-06-10", "2026-06-17", "completed", "4 种角色、成员管理、邀请系统"),
    )

    permission_tasks = [
        ("WorkspaceMembership 实体", "成员关系实体设计", "completed", "high"),
        ("WorkspaceRole 枚举", "owner/admin/member/viewer", "completed", "high"),
        ("权限检查中间件", "基于角色的访问控制", "completed", "high"),
        ("数据隔离过滤器", "确保跨租户数据隔离", "completed", "high"),
        ("邀请成员 API", "发送邀请邮件", "completed", "high"),
        ("接受/拒绝邀请 API", "处理邀请响应", "completed", "medium"),
        ("移除成员 API", "删除成员关系", "completed", "medium"),
        ("修改成员角色 API", "角色变更", "completed", "medium"),
        ("转让 Workspace 所有权", "转让 owner 角色", "completed", "low"),
        ("权限矩阵验证", "测试所有权限组合", "completed", "high"),
    ]

    for name, desc, status, priority in permission_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 4", "多租户权限体系", priority, datetime.now().isoformat()),
        )

    # Milestone 3: 订阅与计费
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("订阅与计费体系", "Phase 4", "2026-06-10", "2026-06-17", "completed", "Free/Pro/Enterprise 套餐"),
    )

    subscription_tasks = [
        ("Subscription 实体与 Repository", "订阅数据模型", "completed", "high"),
        ("SubscriptionPlan 枚举", "free/pro/enterprise", "completed", "high"),
        ("配额检查工具", "检查项目数量、存储限制", "completed", "high"),
        ("套餐限制中间件", "API 调用时检查配额", "completed", "high"),
        ("支付宝 SDK 集成", "支付宝支付接口", "pending", "medium"),
        ("微信支付 SDK 集成", "微信支付接口", "pending", "medium"),
        ("创建支付订单 API", "生成支付订单", "pending", "medium"),
        ("支付回调处理", "处理支付通知", "pending", "medium"),
        ("Invoice 实体与 Repository", "账单数据模型", "completed", "medium"),
        ("生成账单 PDF", "PDF 账单生成", "pending", "low"),
    ]

    for name, desc, status, priority in subscription_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 4", "订阅与计费体系", priority, datetime.now().isoformat()),
        )

    print("[OK] Phase 4 任务已录入")

    # ========== Phase 6: 前端完善 ==========
    print("\n[Phase 6] 初始化任务...")

    # Milestone 1: 基础搭建
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("前端基础搭建", "Phase 6", "2026-06-17", "2026-06-17", "completed", "Vite + React + TypeScript"),
    )

    foundation_tasks = [
        ("项目初始化：Vite + React + TypeScript", "创建 Vite 项目", "completed", "high"),
        ("安装配置依赖包", "Ant Design, React Router 等", "completed", "high"),
        ("搭建基础布局组件", "Header, Sidebar, Footer", "completed", "high"),
        ("API 客户端封装", "Axios 拦截器和 token 管理", "completed", "high"),
        ("路由配置", "React Router 路由定义", "completed", "high"),
        ("设计系统配置", "CSS 变量、色彩系统", "completed", "medium"),
        ("TypeScript 类型定义", "API 响应、实体类型", "completed", "medium"),
    ]

    for name, desc, status, priority in foundation_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 6", "前端基础搭建", priority, datetime.now().isoformat()),
        )

    # Milestone 2: 认证页面
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("认证系统", "Phase 6", "2026-06-17", "2026-06-17", "completed", "登录、注册、密码重置"),
    )

    auth_ui_tasks = [
        ("登录页面", "用户登录界面和逻辑", "completed", "high"),
        ("注册页面", "用户注册界面和验证", "completed", "high"),
        ("忘记密码页面", "密码重置请求", "completed", "high"),
        ("重置密码页面", "密码重置界面", "completed", "high"),
        ("Token 管理和刷新", "自动 token 刷新", "completed", "high"),
    ]

    for name, desc, status, priority in auth_ui_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 6", "认证系统", priority, datetime.now().isoformat()),
        )

    # Milestone 3: 工作空间管理
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("工作空间管理", "Phase 6", "2026-06-17", "2026-06-17", "completed", "工作空间 CRUD、成员管理"),
    )

    workspace_tasks = [
        ("工作空间列表页面", "显示所有工作空间", "completed", "high"),
        ("工作空间详情页面", "工作空间概览、配额", "completed", "high"),
        ("成员列表和管理", "成员列表、角色修改", "completed", "high"),
        ("邀请成员功能", "邀请成员弹窗", "completed", "high"),
        ("权限矩阵展示", "各角色权限说明", "completed", "medium"),
        ("工作空间设置", "修改名称、删除", "completed", "medium"),
    ]

    for name, desc, status, priority in workspace_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 6", "工作空间管理", priority, datetime.now().isoformat()),
        )

    # Milestone 4: 订阅管理
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("订阅管理", "Phase 6", "2026-06-17", "2026-06-17", "completed", "套餐选择、升级流程"),
    )

    subscription_ui_tasks = [
        ("套餐选择页面", "Free/Pro/Enterprise 对比", "completed", "high"),
        ("升级流程", "订阅升级流程和确认", "completed", "high"),
        ("配额展示组件", "项目数量、存储使用", "completed", "high"),
        ("账单页面", "历史账单列表", "completed", "medium"),
        ("发票申请入口", "发票申请表单", "completed", "low"),
    ]

    for name, desc, status, priority in subscription_ui_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 6", "订阅管理", priority, datetime.now().isoformat()),
        )

    # Milestone 5: Admin 后台
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("Admin 后台", "Phase 6", "2026-06-17", "2026-06-17", "completed", "Dashboard、用户管理"),
    )

    admin_tasks = [
        ("Dashboard 仪表盘", "关键指标和图表", "completed", "high"),
        ("用户管理页面", "用户列表、搜索", "completed", "high"),
        ("用户操作功能", "封禁、解封、重置密码", "completed", "high"),
        ("系统监控页面", "API 性能、数据库状态", "completed", "medium"),
        ("日志查看器", "错误日志和慢查询", "completed", "medium"),
    ]

    for name, desc, status, priority in admin_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 6", "Admin 后台", priority, datetime.now().isoformat()),
        )

    # Milestone 6: 个人中心
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("个人中心", "Phase 6", "2026-06-17", "2026-06-17", "completed", "个人设置、安全设置"),
    )

    profile_tasks = [
        ("个人设置页面", "基本信息、头像上传", "completed", "medium"),
        ("账号安全设置", "修改密码、修改邮箱", "completed", "high"),
        ("通知设置", "邮件通知、类型选择", "completed", "medium"),
        ("Session 管理", "设备列表、登出设备", "completed", "medium"),
    ]

    for name, desc, status, priority in profile_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 6", "个人中心", priority, datetime.now().isoformat()),
        )

    # Milestone 7: 测试与优化
    cursor.execute(
        """
        INSERT INTO milestones (name, phase, start_date, end_date, status, description)
        VALUES (?, ?, ?, ?, ?, ?)
    """,
        ("测试与优化", "Phase 6", "2026-06-17", "2026-06-17", "completed", "单元测试、E2E 测试、性能优化"),
    )

    test_tasks = [
        ("单元测试", "Vitest + React Testing Library", "completed", "high"),
        ("E2E 测试：认证流程", "Playwright 自动化测试", "completed", "high"),
        ("E2E 测试：工作空间", "工作空间管理流程测试", "completed", "high"),
        ("E2E 测试：订阅管理", "订阅升级流程测试", "completed", "medium"),
        ("性能优化：代码分割", "Vendor chunks 分割", "completed", "high"),
        ("性能优化：图片和资源", "压缩和懒加载", "completed", "medium"),
        ("可访问性优化", "WCAG 2.1 AA 标准", "completed", "medium"),
        ("移动端适配优化", "响应式设计验证", "completed", "medium"),
    ]

    for name, desc, status, priority in test_tasks:
        cursor.execute(
            """
            INSERT INTO tasks (name, description, status, phase, milestone, priority, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
            (name, desc, status, "Phase 6", "测试与优化", priority, datetime.now().isoformat()),
        )

    print("[OK] Phase 6 任务已录入")

    conn.commit()

    # 统计
    cursor.execute("SELECT COUNT(*) FROM milestones")
    milestone_count = cursor.fetchone()[0]

    cursor.execute("SELECT COUNT(*) FROM tasks")
    task_count = cursor.fetchone()[0]

    cursor.execute("SELECT phase, COUNT(*) FROM tasks GROUP BY phase")
    phase_stats = cursor.fetchall()

    conn.close()

    print("\n" + "=" * 60)
    print("[SUCCESS] 数据初始化完成！")
    print("=" * 60)
    print(f"✅ 里程碑总数: {milestone_count}")
    print(f"✅ 任务总数: {task_count}")
    print("\n各 Phase 任务统计:")
    for phase, count in phase_stats:
        print(f"  - {phase}: {count} 个任务")
    print("\n推进器地址: http://47.98.113.167:8088/projects")
    print("=" * 60)


if __name__ == "__main__":
    init_database()
