#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
小虾 SaaS 项目推进器数据初始化脚本
将当前项目状态、规则、待办事项录入推进器
"""

import io
import sys

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")

import json
from datetime import datetime, timedelta

import requests

API_BASE = "http://47.98.113.167:8089/api/v1"

# 临时创建项目和工作空间（实际应该从数据库获取）
# 这里用固定的 UUID 模拟
PROJECT_ID = "00000000-0000-0000-0000-000000000001"
WORKSPACE_ID = "00000000-0000-0000-0000-000000000001"


def create_milestone(name, target_date, description=""):
    """创建里程碑"""
    payload = {
        "name": name,
        "target_date": target_date,
        "project_id": PROJECT_ID,
        "description": description,
    }
    resp = requests.post(f"{API_BASE}/project-management/milestones", json=payload)
    if resp.status_code == 200:
        print(f"[OK] 里程碑创建成功: {name}")
        return resp.json()
    else:
        print(f"[FAIL] 里程碑创建失败: {name} - {resp.text}")
        return None


def create_task(name, description, priority="medium", status="pending", progress=0, tags=None):
    """创建任务"""
    payload = {
        "name": name,
        "description": description,
        "project_id": PROJECT_ID,
        "priority": priority,
    }
    resp = requests.post(f"{API_BASE}/project-management/tasks", json=payload)
    if resp.status_code == 200:
        print(f"[OK] 任务创建成功: {name}")
        return resp.json()
    else:
        print(f"[FAIL] 任务创建失败: {name} - {resp.text}")
        return None


def main():
    print("=" * 60)
    print("小虾 SaaS 项目推进器 - 数据初始化")
    print("=" * 60)

    # ========== 里程碑 ==========
    print("\n[1/4] 创建里程碑...")

    milestones = [
        {
            "name": "Phase 1: 核心平台层完成",
            "target_date": "2026-06-15",
            "description": "Clean Architecture 骨架 + 核心业务对象 + 完整测试",
        },
        {
            "name": "Phase 2: 项目管理模块落地",
            "target_date": "2026-06-16",
            "description": "任务/里程碑/问题管理 + 前后端完整链路",
        },
        {
            "name": "Phase 3: 部署与备案完成",
            "target_date": "2026-06-30",
            "description": "生产环境部署 + HTTPS 证书 + 域名备案通过",
        },
        {
            "name": "Phase 4: SAAS 产品化完成",
            "target_date": "2026-07-15",
            "description": "多租户 + 权限体系 + 订阅计费",
        },
        {
            "name": "Phase 5: AI 剪辑能力接入",
            "target_date": "2026-08-01",
            "description": "视频分类模型 + 自动剪辑 + 配音合成",
        },
    ]

    for m in milestones:
        create_milestone(m["name"], m["target_date"], m["description"])

    # ========== 已完成任务 ==========
    print("\n[OK] 录入已完成任务...")

    completed_tasks = [
        {
            "name": "Clean Architecture 架构设计",
            "description": "Domain → Ports → Application → Adapters 分层完成",
            "status": "COMPLETED",
            "progress": 100,
            "priority": "urgent",
            "tags": ["架构", "Phase1"],
        },
        {
            "name": "核心业务对象实现",
            "description": "User/Workspace/Project/AssetLibrary/Asset/IngestJob/ClassificationJob 全部完成",
            "status": "COMPLETED",
            "progress": 100,
            "priority": "high",
            "tags": ["业务逻辑", "Phase1"],
        },
        {
            "name": "双持久化实现",
            "description": "In-Memory (测试) + SQLAlchemy (生产) 完成",
            "status": "COMPLETED",
            "progress": 100,
            "priority": "high",
            "tags": ["数据库", "Phase1"],
        },
        {
            "name": "项目管理模块开发",
            "description": "任务/里程碑/问题 三大实体 + 11 个 Use Cases + 11 个 API",
            "status": "COMPLETED",
            "progress": 100,
            "priority": "urgent",
            "tags": ["项目管理", "Phase2"],
        },
        {
            "name": "项目推进器前端开发",
            "description": "5 个页面 + 3 个表单 + 完整前后端集成",
            "status": "COMPLETED",
            "progress": 100,
            "priority": "high",
            "tags": ["前端", "Phase2"],
        },
        {
            "name": "Docker Compose 部署",
            "description": "5 个容器 (postgres/redis/api/worker/web) 全部运行",
            "status": "COMPLETED",
            "progress": 100,
            "priority": "high",
            "tags": ["部署", "Phase3"],
        },
        {
            "name": "Nginx 反向代理配置",
            "description": "8088/8089 临时端口配置完成，绕过备案限制",
            "status": "COMPLETED",
            "progress": 100,
            "priority": "medium",
            "tags": ["部署", "Phase3"],
        },
    ]

    for task in completed_tasks:
        create_task(**task)

    # ========== 进行中任务 ==========
    print("\n[2/4] 录入进行中任务...")

    in_progress_tasks = [
        {
            "name": "域名备案审核",
            "description": "saas.xiaoxiajianji.com / saas-api.xiaoxiajianji.com 等待工信部审核通过",
            "status": "IN_PROGRESS",
            "progress": 50,
            "priority": "urgent",
            "tags": ["部署", "Phase3", "阻塞"],
        },
        {
            "name": "HTTPS 证书申请",
            "description": "Let's Encrypt 证书，等待备案通过后申请",
            "status": "BLOCKED",
            "progress": 0,
            "priority": "high",
            "tags": ["部署", "Phase3", "依赖备案"],
        },
    ]

    for task in in_progress_tasks:
        create_task(**task)

    # ========== 待办任务 ==========
    print("\n[3/4] 录入待办任务...")

    pending_tasks = [
        {
            "name": "切换到正式域名和 HTTPS",
            "description": "备案通过后：改回 80/443 端口 + 申请证书 + nginx 配置 HTTPS",
            "status": "PENDING",
            "progress": 0,
            "priority": "high",
            "tags": ["部署", "Phase3", "依赖备案"],
        },
        {
            "name": "PostgreSQL 生产环境切换",
            "description": "当前用 In-Memory，需切换到 PostgreSQL + 数据持久化验证",
            "status": "PENDING",
            "progress": 0,
            "priority": "high",
            "tags": ["数据库", "Phase3"],
        },
        {
            "name": "前端环境变量配置",
            "description": "API 地址从临时端口改为正式域名 https://saas-api.xiaoxiajianji.com",
            "status": "PENDING",
            "progress": 0,
            "priority": "medium",
            "tags": ["前端", "Phase3", "依赖备案"],
        },
        {
            "name": "甘特图视图开发",
            "description": "项目推进器增加甘特图/时间线视图，可视化任务时间规划",
            "status": "PENDING",
            "progress": 0,
            "priority": "medium",
            "tags": ["前端", "Phase2"],
        },
        {
            "name": "批量操作 API",
            "description": "任务批量更新状态/优先级/删除接口",
            "status": "PENDING",
            "progress": 0,
            "priority": "low",
            "tags": ["后端", "Phase2"],
        },
        {
            "name": "数据导出功能",
            "description": "导出任务列表为 Excel/CSV",
            "status": "PENDING",
            "progress": 0,
            "priority": "low",
            "tags": ["功能", "Phase2"],
        },
        {
            "name": "多租户权限体系",
            "description": "Workspace 级别权限控制 + 用户角色管理",
            "status": "PENDING",
            "progress": 0,
            "priority": "urgent",
            "tags": ["权限", "Phase4"],
        },
        {
            "name": "认证与账号体系",
            "description": "JWT 登录 + 注册 + 密码重置",
            "status": "PENDING",
            "progress": 0,
            "priority": "urgent",
            "tags": ["认证", "Phase4"],
        },
        {
            "name": "订阅与计费体系",
            "description": "SaaS 订阅套餐 + 支付接入（微信/支付宝）",
            "status": "PENDING",
            "progress": 0,
            "priority": "high",
            "tags": ["商业化", "Phase4"],
        },
        {
            "name": "视频分类模型接入",
            "description": "真实 AI 模型替换占位分类逻辑",
            "status": "PENDING",
            "progress": 0,
            "priority": "urgent",
            "tags": ["AI", "Phase5"],
        },
        {
            "name": "自动剪辑能力",
            "description": "视频自动剪辑 + 转场特效 + 字幕生成",
            "status": "PENDING",
            "progress": 0,
            "priority": "high",
            "tags": ["AI", "Phase5"],
        },
        {
            "name": "配音合成能力",
            "description": "AI 配音 + 音频混音",
            "status": "PENDING",
            "progress": 0,
            "priority": "medium",
            "tags": ["AI", "Phase5"],
        },
    ]

    for task in pending_tasks:
        create_task(**task)

    print("\n" + "=" * 60)
    print("[OK] 数据初始化完成！")
    print("=" * 60)
    print(f"\n访问推进器: http://47.98.113.167:8088/projects")
    print(f"访问 API 文档: http://47.98.113.167:8089/docs\n")


if __name__ == "__main__":
    main()
