#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Phase 4 任务数据初始化脚本
将认证、权限、订阅计费的所有任务录入推进器
"""

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"
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"):
    """创建任务"""
    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}")
        return None


def main():
    print("=" * 60)
    print("Phase 4: SAAS 产品化 - 任务初始化")
    print("=" * 60)

    # ========== Milestone 1: 认证与账号体系 ==========
    print("\n[1/4] 创建里程碑：认证与账号体系...")
    create_milestone("认证与账号体系", "2026-06-23", "JWT 登录、注册、密码管理、Session 管理")

    print("\n  录入任务...")

    # Day 1-2: 基础设施
    create_task("JWT 工具类实现", "sign/verify/refresh Token 功能", "high")
    create_task("bcrypt 密码哈希工具", "密码加密存储", "high")
    create_task("Redis Session 存储", "refresh_token 存储和管理", "high")
    create_task("邮件服务封装", "SMTP + 邮件模板（欢迎/验证/重置）", "medium")
    create_task("User 实体扩展", "新增 password_hash/email_verified 等字段", "high")

    # Day 3-4: 核心认证
    create_task("注册 API", "邮箱 + 密码注册，发送验证邮件", "urgent")
    create_task("登录 API", "JWT 签发 access_token + refresh_token", "urgent")
    create_task("登出 API", "撤销 refresh_token", "high")
    create_task("刷新 Token API", "用 refresh_token 换取新 access_token", "high")
    create_task("密码重置流程", "忘记密码 + 邮件重置链接", "medium")

    # Day 5-6: Session 管理
    create_task("Session 实体与 Repository", "存储设备信息、IP、过期时间", "medium")
    create_task("活跃 Session 列表 API", "查看所有登录设备", "low")
    create_task("强制登出所有设备", "撤销所有 refresh_token", "medium")
    create_task("设备信息解析", "解析 User-Agent 识别设备类型", "low")

    # Day 7: 测试与文档
    create_task("认证集成测试", "注册/登录/登出/刷新完整流程", "high")
    create_task("认证安全测试", "密码强度/Token 伪造/暴力破解防护", "urgent")
    create_task("认证 API 文档更新", "OpenAPI 规范更新", "low")

    # ========== Milestone 2: 多租户权限体系 ==========
    print("\n[2/4] 创建里程碑：多租户权限体系...")
    create_milestone("多租户权限体系", "2026-06-30", "4 种角色、成员管理、邀请系统、数据隔离")

    print("\n  录入任务...")

    # Day 1-2: 权限基础
    create_task("WorkspaceMembership 实体", "成员关系、角色存储", "high")
    create_task("WorkspaceRole 枚举", "Owner/Admin/Member/Viewer 权限定义", "high")
    create_task("权限检查中间件", "@require_permission 装饰器", "urgent")

    # Day 3-4: 成员管理
    create_task("邀请成员 API", "发送邀请邮件 + 生成邀请令牌", "high")
    create_task("接受/拒绝邀请 API", "处理邀请状态", "high")
    create_task("移除成员 API", "删除 WorkspaceMembership", "medium")
    create_task("修改成员角色 API", "Owner/Admin 可修改其他人角色", "medium")
    create_task("转让 Workspace 所有权", "Owner 转让给其他成员", "low")

    # Day 5-6: 权限验证
    create_task("为所有现有 API 加权限检查", "项目/任务/素材 API 权限保护", "urgent")
    create_task("跨 Workspace 访问防护测试", "确保数据隔离无漏洞", "urgent")
    create_task("权限矩阵验证", "测试各角色权限边界", "high")

    # Day 7: 测试与文档
    create_task("权限系统集成测试", "各角色操作权限完整测试", "high")
    create_task("数据隔离安全测试", "跨 Workspace 攻击测试", "urgent")
    create_task("权限 API 文档更新", "成员管理 API 文档", "low")

    # ========== Milestone 3: 订阅与计费 ==========
    print("\n[3/4] 创建里程碑：订阅与计费...")
    create_milestone("订阅与计费体系", "2026-07-07", "3 种套餐、支付宝/微信支付、账单管理")

    print("\n  录入任务...")

    # Day 1-2: 订阅基础
    create_task("Subscription 实体与 Repository", "订阅状态、套餐、到期时间", "high")
    create_task("SubscriptionPlan 枚举", "free/pro/enterprise 套餐定义", "high")
    create_task("配额检查工具", "检查 Workspace/项目/存储限制", "high")
    create_task("套餐限制中间件", "创建资源前检查配额", "urgent")

    # Day 3-4: 支付集成
    create_task("支付宝 SDK 集成", "生成支付二维码", "high")
    create_task("微信支付 SDK 集成", "生成支付二维码", "high")
    create_task("创建支付订单 API", "用户选择套餐 → 生成订单", "high")
    create_task("支付回调处理", "验证签名 + 更新订单状态 + 激活订阅", "urgent")

    # Day 5-6: 账单管理
    create_task("Invoice 实体与 Repository", "账单记录存储", "medium")
    create_task("生成账单 PDF", "使用模板生成 PDF 发票", "low")
    create_task("账单列表/下载 API", "用户查看历史账单", "medium")
    create_task("订阅历史记录", "订阅变更历史追踪", "low")

    # Day 7: 测试与文档
    create_task("支付流程端到端测试", "沙箱环境完整支付流程", "high")
    create_task("配额检查测试", "超出限制时正确拦截", "high")
    create_task("计费 API 文档更新", "订阅/支付/账单 API 文档", "low")

    # ========== Milestone 4: 前端集成与上线 ==========
    print("\n[4/4] 创建里程碑：前端集成与上线...")
    create_milestone("前端集成与上线", "2026-07-14", "认证 UI、权限 UI、订阅 UI、端到端测试、生产部署")

    print("\n  录入任务...")

    # Day 1-2: 认证 UI
    create_task("登录页面", "邮箱/密码登录表单 + 记住我", "high")
    create_task("注册页面", "邮箱注册 + 密码强度提示", "high")
    create_task("忘记密码页面", "邮箱重置流程", "medium")
    create_task("邮箱验证提示", "注册后验证邮件提醒", "low")

    # Day 3-4: 权限 UI
    create_task("成员管理页面", "Workspace 成员列表 + 角色显示", "high")
    create_task("邀请成员弹窗", "输入邮箱 + 选择角色", "medium")
    create_task("角色选择器组件", "下拉选择 Owner/Admin/Member/Viewer", "low")
    create_task("权限说明文档", "各角色权限说明页面", "low")

    # Day 5-6: 订阅 UI
    create_task("套餐选择页面", "免费版/专业版/企业版对比表", "high")
    create_task("支付二维码页面", "显示支付宝/微信二维码 + 轮询支付状态", "high")
    create_task("账单管理页面", "历史账单列表 + 下载", "medium")
    create_task("配额使用展示", "当前 Workspace/项目/存储使用情况", "medium")

    # Day 7: 上线准备
    create_task("Phase 4 端到端测试", "注册 → 邀请成员 → 付费 → 使用完整流程", "urgent")
    create_task("Phase 4 性能测试", "登录/权限检查响应时间测试", "high")
    create_task("Phase 4 安全审计", "SQL注入/XSS/CSRF/Token安全检查", "urgent")
    create_task("Phase 4 生产环境部署", "部署到服务器 + 灰度发布", "high")

    print("\n" + "=" * 60)
    print("[OK] Phase 4 所有任务已录入推进器！")
    print("=" * 60)
    print("\n访问推进器: http://47.98.113.167:8088/projects")
    print("共创建 4 个里程碑 + 68 个任务\n")


if __name__ == "__main__":
    main()
