/**
 * SF-02 — Strategy → Requirement Conversion Engine
 *
 * Part B：将 SF-01 Product Strategy Package 自动转换为需求体系。
 *
 * 输入：Product Strategy Package (from SF-01)
 * 输出：Epic / Feature / User Story / Acceptance Criteria
 *
 * 核心逻辑：
 *   从 Problem Statement → 推导核心 Epics
 *   从 Target Customer → 推导用户角色和权限需求
 *   从 Roadmap MVP → 推导 MVP 范围
 *   从 Value Proposition → 推导 Functional Requirements
 *
 * 设计原则：
 *   - 领域知识驱动（非 LLM），确定性转换
 *   - 基于产品分类的域模板映射
 *   - 禁止：代码生成、数据库设计、架构设计、UI 设计
 *
 * @module sf-02-requirement-engineering/strategy-to-requirement
 * @since SF-02
 */

import {
  createEpic, EPIC_CATEGORY,
  createFeature, createUserStory, STORY_PRIORITY,
  createAcceptanceCriteria,
  createBusinessRule, RULE_TYPE,
  createNonFunctionalRequirement, NFR_CATEGORY,
  createPermissionRequirement, ACCESS_MODEL, ROLE_TYPE,
  createIntegrationRequirement, INTEGRATION_CATEGORY,
  createDataRequirement, DATA_CLASSIFICATION, DATA_LIFECYCLE,
} from "./domain-model.mjs";

// ═══════════════════════════════════════════════════════
// Product Category → Domain Template Mapping
// ═══════════════════════════════════════════════════════

/**
 * 产品分类 → 默认 Epic 模板。
 *
 * 每个产品分类有自己专属的 Epic 集合。
 * 当无法精确匹配时使用 "通用" 模板。
 */
const CATEGORY_EPIC_TEMPLATES = Object.freeze({
  "AI平台": [
    { title: "用户管理", category: EPIC_CATEGORY.USER_MANAGEMENT, desc: "用户注册、登录、个人信息管理、团队管理", objective: "建立完整的用户身份体系" },
    { title: "知识库管理", category: EPIC_CATEGORY.CONTENT_MANAGEMENT, desc: "知识文档的上传、解析、分类、索引、版本管理", objective: "构建高质量可检索的知识体系" },
    { title: "Agent管理", category: EPIC_CATEGORY.AI_ML, desc: "AI Agent 的创建、配置、训练、版本管理", objective: "实现 Agent 全生命周期管理" },
    { title: "对话管理", category: EPIC_CATEGORY.BUSINESS_PROCESS, desc: "对话会话管理、多轮对话、上下文记忆", objective: "提供流畅的 AI 对话体验" },
    { title: "权限管理", category: EPIC_CATEGORY.SECURITY, desc: "RBAC 权限控制、数据隔离、操作审计", objective: "保证系统安全性" },
    { title: "运营分析", category: EPIC_CATEGORY.ANALYTICS, desc: "对话分析、用户行为分析、知识效果评估、成本分析", objective: "数据驱动的产品优化" },
    { title: "系统设置", category: EPIC_CATEGORY.SYSTEM, desc: "系统参数配置、模型配置、通知配置、集成管理", objective: "灵活的系统管理能力" },
    { title: "集成对接", category: EPIC_CATEGORY.INTEGRATION, desc: "第三方系统集成、API开放平台、Webhook", objective: "开放生态集成能力" },
  ],
  "企业SaaS": [
    { title: "用户与组织管理", category: EPIC_CATEGORY.USER_MANAGEMENT, desc: "组织架构、用户管理、角色权限", objective: "企业级用户管理" },
    { title: "核心业务管理", category: EPIC_CATEGORY.BUSINESS_PROCESS, desc: "核心业务流程的数字化管理", objective: "业务流程自动化" },
    { title: "协作与沟通", category: EPIC_CATEGORY.EXPERIENCE, desc: "团队协作、消息通知、审批流程", objective: "高效团队协作" },
    { title: "数据分析与报表", category: EPIC_CATEGORY.ANALYTICS, desc: "业务数据分析、自定义报表、大屏展示", objective: "数据驱动决策" },
    { title: "权限与安全", category: EPIC_CATEGORY.SECURITY, desc: "数据权限、操作审计、合规管理", objective: "企业级安全保障" },
    { title: "系统管理与配置", category: EPIC_CATEGORY.SYSTEM, desc: "系统配置、租户管理、日志管理", objective: "灵活的运维管理" },
    { title: "集成与开放平台", category: EPIC_CATEGORY.INTEGRATION, desc: "第三方集成、API管理、单点登录", objective: "开放生态集成" },
  ],
  "电商平台": [
    { title: "用户管理", category: EPIC_CATEGORY.USER_MANAGEMENT, desc: "买家/卖家注册、登录、会员体系", objective: "多角色用户体系" },
    { title: "商品管理", category: EPIC_CATEGORY.CONTENT_MANAGEMENT, desc: "商品发布、SKU管理、库存管理", objective: "完整商品生命周期" },
    { title: "订单管理", category: EPIC_CATEGORY.BUSINESS_PROCESS, desc: "下单、支付、发货、退货全流程", objective: "顺畅交易体验" },
    { title: "支付管理", category: EPIC_CATEGORY.INTEGRATION, desc: "多支付渠道集成、对账、退款", objective: "安全便捷支付" },
    { title: "营销管理", category: EPIC_CATEGORY.BUSINESS_PROCESS, desc: "优惠券、活动、推荐、会员营销", objective: "增长驱动" },
    { title: "数据分析", category: EPIC_CATEGORY.ANALYTICS, desc: "销售分析、用户分析、商品分析", objective: "精细化运营" },
    { title: "系统管理", category: EPIC_CATEGORY.SYSTEM, desc: "权限管理、系统配置、日志审计", objective: "平台运维" },
  ],
  "教育平台": [
    { title: "用户管理", category: EPIC_CATEGORY.USER_MANAGEMENT, desc: "学生/教师/管理员多角色管理", objective: "多角色用户体系" },
    { title: "课程管理", category: EPIC_CATEGORY.CONTENT_MANAGEMENT, desc: "课程创建、章节管理、资源上传", objective: "结构化课程体系" },
    { title: "学习管理", category: EPIC_CATEGORY.BUSINESS_PROCESS, desc: "学习进度、作业提交、考试测评", objective: "完整学习闭环" },
    { title: "互动社区", category: EPIC_CATEGORY.EXPERIENCE, desc: "讨论区、问答、学习小组", objective: "学习社交体验" },
    { title: "数据分析", category: EPIC_CATEGORY.ANALYTICS, desc: "学习分析、成绩统计、教学质量评估", objective: "教学效果量化" },
    { title: "系统管理", category: EPIC_CATEGORY.SYSTEM, desc: "权限管理、机构管理、配置管理", objective: "多租户管理" },
  ],
  "通用": [
    { title: "用户管理", category: EPIC_CATEGORY.USER_MANAGEMENT, desc: "用户注册、登录、个人信息、认证", objective: "用户身份与权限管理" },
    { title: "内容管理", category: EPIC_CATEGORY.CONTENT_MANAGEMENT, desc: "内容创建、编辑、发布、管理", objective: "内容全生命周期管理" },
    { title: "业务流程", category: EPIC_CATEGORY.BUSINESS_PROCESS, desc: "核心业务流程管理", objective: "业务流程数字化" },
    { title: "运营分析", category: EPIC_CATEGORY.ANALYTICS, desc: "数据统计、报表、分析", objective: "数据驱动运营" },
    { title: "系统设置", category: EPIC_CATEGORY.SYSTEM, desc: "系统配置、参数管理、通知", objective: "系统灵活配置" },
    { title: "权限管理", category: EPIC_CATEGORY.SECURITY, desc: "角色权限、数据安全、审计", objective: "系统安全合规" },
  ],
});

/**
 * 产品分类 → 集成需求模板。
 */
const CATEGORY_INTEGRATION_TEMPLATES = Object.freeze({
  "AI平台": [
    { name: "AI模型服务", category: INTEGRATION_CATEGORY.AI_MODEL, desc: "LLM API 集成、模型管理", necessity: "required", providers: ["OpenAI", "DeepSeek", "Anthropic", "GLM"] },
    { name: "邮件服务", category: INTEGRATION_CATEGORY.EMAIL, desc: "验证邮件、通知邮件", necessity: "required", providers: ["SendGrid", "AWS SES", "Resend"] },
    { name: "短信服务", category: INTEGRATION_CATEGORY.SMS, desc: "验证码、通知短信", necessity: "optional", providers: ["Twilio", "阿里云短信"] },
    { name: "对象存储", category: INTEGRATION_CATEGORY.OBJECT_STORAGE, desc: "文件上传、知识文档存储", necessity: "required", providers: ["AWS S3", "OSS", "MinIO"] },
    { name: "搜索引擎", category: INTEGRATION_CATEGORY.SEARCH, desc: "知识库全文检索", necessity: "required", providers: ["Elasticsearch", "Meilisearch"] },
    { name: "第三方登录", category: INTEGRATION_CATEGORY.THIRD_PARTY_AUTH, desc: "OAuth 社交登录", necessity: "optional", providers: ["Google", "GitHub", "微信"] },
  ],
  "电商平台": [
    { name: "支付系统", category: INTEGRATION_CATEGORY.PAYMENT, desc: "多渠道支付集成", necessity: "required", providers: ["Stripe", "支付宝", "微信支付"] },
    { name: "短信服务", category: INTEGRATION_CATEGORY.SMS, desc: "订单通知、验证码", necessity: "required", providers: ["Twilio", "阿里云短信"] },
    { name: "邮件服务", category: INTEGRATION_CATEGORY.EMAIL, desc: "营销邮件、订单通知", necessity: "required", providers: ["SendGrid", "AWS SES"] },
    { name: "对象存储", category: INTEGRATION_CATEGORY.OBJECT_STORAGE, desc: "商品图片存储", necessity: "required", providers: ["AWS S3", "OSS"] },
    { name: "搜索引擎", category: INTEGRATION_CATEGORY.SEARCH, desc: "商品搜索", necessity: "required", providers: ["Elasticsearch"] },
    { name: "CDN", category: INTEGRATION_CATEGORY.CDN, desc: "静态资源加速", necessity: "required", providers: ["Cloudflare", "AWS CloudFront"] },
    { name: "消息队列", category: INTEGRATION_CATEGORY.MESSAGE_QUEUE, desc: "订单异步处理", necessity: "required", providers: ["RabbitMQ", "Kafka", "Redis"] },
  ],
  "企业SaaS": [
    { name: "第三方登录", category: INTEGRATION_CATEGORY.THIRD_PARTY_AUTH, desc: "企业SSO登录", necessity: "required", providers: ["LDAP", "SAML", "OIDC"] },
    { name: "邮件服务", category: INTEGRATION_CATEGORY.EMAIL, desc: "通知邮件、报告邮件", necessity: "required", providers: ["SendGrid", "AWS SES"] },
    { name: "消息队列", category: INTEGRATION_CATEGORY.MESSAGE_QUEUE, desc: "异步任务处理", necessity: "optional", providers: ["RabbitMQ", "Kafka"] },
    { name: "监控服务", category: INTEGRATION_CATEGORY.MONITORING, desc: "系统监控告警", necessity: "required", providers: ["Datadog", "Grafana"] },
  ],
  "教育平台": [
    { name: "视频/存储服务", category: INTEGRATION_CATEGORY.OBJECT_STORAGE, desc: "课程视频存储与分发", necessity: "required", providers: ["AWS S3", "OSS", "VOD"] },
    { name: "支付系统", category: INTEGRATION_CATEGORY.PAYMENT, desc: "课程购买支付", necessity: "conditional", providers: ["Stripe", "支付宝"] },
    { name: "邮件服务", category: INTEGRATION_CATEGORY.EMAIL, desc: "学习提醒、通知", necessity: "required", providers: ["SendGrid"] },
  ],
});

// ═══════════════════════════════════════════════════════
// Engine 1: Epic Generator
// ═══════════════════════════════════════════════════════

/**
 * 从产品分类获取 Epic 模板，生成 Epic 列表。
 *
 * @param {object} strategyPackage — SF-01 Strategy Package
 * @returns {object[]} Epic 列表
 */
export function generateEpicsFromStrategy(strategyPackage) {
  const category = strategyPackage?.metadata?.category || "通用";

  // 模糊匹配分类
  let templates = CATEGORY_EPIC_TEMPLATES["通用"];
  for (const [key, tmpl] of Object.entries(CATEGORY_EPIC_TEMPLATES)) {
    if (key === "通用") continue;
    if (category.includes(key.replace(/平台|SaaS/g, "")) || key.includes(category)) {
      templates = tmpl;
      break;
    }
  }

  return templates.map(t => createEpic({
    title: t.title,
    description: t.desc,
    category: t.category,
    objective: t.objective,
    successMetric: `${t.title}功能覆盖率 100%`,
  }));
}

// ═══════════════════════════════════════════════════════
// Engine 2: Feature Generator (per Epic)
// ═══════════════════════════════════════════════════════

const EPIC_FEATURE_TEMPLATES = Object.freeze({
  "用户管理": [
    { title: "用户注册", desc: "支持邮箱/手机/第三方注册", type: "CRUD", value: "降低用户注册门槛" },
    { title: "用户登录", desc: "支持密码/验证码/第三方登录", type: "CRUD", value: "安全便捷的身份认证" },
    { title: "个人信息管理", desc: "用户编辑个人资料、头像、偏好设置", type: "CRUD", value: "个性化用户体验" },
    { title: "密码管理", desc: "修改密码、重置密码、密码强度检查", type: "CRUD", value: "账户安全" },
  ],
  "用户与组织管理": [
    { title: "组织架构管理", desc: "部门、岗位、职级的创建与维护", type: "CRUD", value: "企业组织数字化" },
    { title: "用户管理", desc: "员工的批量导入、信息管理、状态管理", type: "CRUD", value: "员工全生命周期管理" },
    { title: "角色管理", desc: "系统角色定义与维护", type: "configuration", value: "灵活权限分配" },
    { title: "用户注册与登录", desc: "邮箱/手机/SSO多种注册登录方式", type: "CRUD", value: "安全便捷的访问" },
  ],
  "知识库管理": [
    { title: "知识库创建", desc: "创建知识库、设置基本属性", type: "CRUD", value: "快速搭建知识体系" },
    { title: "文档上传", desc: "支持多种格式文档上传", type: "CRUD", value: "丰富的知识来源" },
    { title: "文档解析", desc: "自动解析文档内容为结构化数据", type: "workflow", value: "自动化知识提取" },
    { title: "知识编辑", desc: "编辑、标注、分类知识条目", type: "CRUD", value: "知识持续优化" },
    { title: "索引构建", desc: "构建全文检索索引", type: "workflow", value: "高效知识检索" },
    { title: "版本管理", desc: "知识版本追踪、回滚", type: "CRUD", value: "知识变更可追溯" },
    { title: "知识分类", desc: "分类体系管理、标签系统", type: "configuration", value: "结构化知识组织" },
  ],
  "Agent管理": [
    { title: "Agent创建", desc: "创建AI Agent实例", type: "CRUD", value: "个性化AI助手" },
    { title: "Agent配置", desc: "配置Agent参数、提示词、工具", type: "configuration", value: "灵活Agent行为控制" },
    { title: "Agent训练", desc: "训练Agent以适配特定场景", type: "workflow", value: "提升Agent准确性" },
    { title: "Agent版本管理", desc: "Agent版本的发布、回滚", type: "CRUD", value: "可控的Agent迭代" },
  ],
  "对话管理": [
    { title: "会话创建", desc: "创建新对话会话", type: "CRUD", value: "用户对话入口" },
    { title: "对话历史", desc: "查看历史对话记录", type: "CRUD", value: "对话可追溯" },
    { title: "多轮对话", desc: "支持上下文感知的多轮对话", type: "workflow", value: "自然的对话体验" },
    { title: "对话导出", desc: "导出对话记录", type: "CRUD", value: "知识沉淀" },
  ],
  "权限管理": [
    { title: "角色管理", desc: "系统角色的CRUD", type: "CRUD", value: "灵活权限分配" },
    { title: "权限分配", desc: "为角色分配资源权限", type: "configuration", value: "精细化权限控制" },
    { title: "操作审计", desc: "记录和查询操作日志", type: "analytics", value: "合规与安全审计" },
  ],
  "权限与安全": [
    { title: "角色与权限管理", desc: "细粒度角色权限定义", type: "configuration", value: "企业安全合规" },
    { title: "数据权限控制", desc: "按组织/区域的数据访问控制", type: "configuration", value: "数据隔离" },
    { title: "操作审计日志", desc: "全操作审计追踪", type: "analytics", value: "合规审计" },
  ],
  "运营分析": [
    { title: "数据看板", desc: "核心指标可视化看板", type: "analytics", value: "一目了然的数据洞察" },
    { title: "用户分析", desc: "用户行为、留存、转化分析", type: "analytics", value: "用户增长优化" },
    { title: "业务报表", desc: "自定义业务报表生成", type: "analytics", value: "灵活的业务分析" },
    { title: "数据导出", desc: "数据导出为Excel/CSV", type: "CRUD", value: "数据二次加工" },
  ],
  "数据分析与报表": [
    { title: "仪表盘", desc: "核心业务指标实时展示", type: "analytics", value: "管理驾驶舱" },
    { title: "自定义报表", desc: "拖拽式报表配置", type: "analytics", value: "灵活业务分析" },
    { title: "数据导出", desc: "多格式数据导出", type: "CRUD", value: "数据二次使用" },
    { title: "大屏展示", desc: "数据大屏可视化", type: "analytics", value: "对外展示" },
  ],
  "系统设置": [
    { title: "基本设置", desc: "系统名称、Logo、主题配置", type: "configuration", value: "品牌定制化" },
    { title: "通知配置", desc: "邮件/短信/站内通知配置", type: "configuration", value: "多渠道触达用户" },
    { title: "日志管理", desc: "系统日志查看与导出", type: "CRUD", value: "故障排查" },
  ],
  "系统管理与配置": [
    { title: "租户管理", desc: "多租户创建、配置、隔离", type: "CRUD", value: "多客户管理" },
    { title: "系统参数配置", desc: "全局参数管理", type: "configuration", value: "灵活系统配置" },
    { title: "日志与监控", desc: "系统日志、性能监控", type: "analytics", value: "系统健康保障" },
  ],
  "集成对接": [
    { title: "API管理", desc: "API Key管理、接口文档", type: "configuration", value: "开放集成能力" },
    { title: "Webhook配置", desc: "事件通知的Webhook配置", type: "configuration", value: "实时事件通知" },
    { title: "第三方集成", desc: "与外部系统的数据同步", type: "integration", value: "生态打通" },
  ],
  "集成与开放平台": [
    { title: "API开放平台", desc: "API文档、SDK、沙箱环境", type: "integration", value: "开发者生态" },
    { title: "SSO集成", desc: "企业单点登录集成", type: "integration", value: "企业便利接入" },
    { title: "第三方应用集成", desc: "与主流企业应用集成", type: "integration", value: "生态协同" },
  ],
  "核心业务管理": [
    { title: "业务流程定义", desc: "可视化流程设计与配置", type: "configuration", value: "业务灵活配置" },
    { title: "任务管理", desc: "任务创建、分配、跟踪", type: "CRUD", value: "高效任务协作" },
    { title: "审批流程", desc: "多级审批、会签、转审", type: "workflow", value: "规范审批管理" },
  ],
  "协作与沟通": [
    { title: "消息通知", desc: "站内消息、邮件、应用推送", type: "notification", value: "及时信息触达" },
    { title: "评论与讨论", desc: "业务对象关联讨论", type: "CRUD", value: "高效团队沟通" },
    { title: "审批管理", desc: "审批流程跟踪与管理", type: "workflow", value: "流程透明化" },
  ],
  "商品管理": [
    { title: "商品发布", desc: "商品信息的创建与发布", type: "CRUD", value: "丰富商品库" },
    { title: "SKU管理", desc: "多规格商品管理", type: "CRUD", value: "灵活商品配置" },
    { title: "库存管理", desc: "库存追踪、预警、调拨", type: "CRUD", value: "精准库存控制" },
    { title: "商品搜索", desc: "全文检索、筛选、排序", type: "search", value: "快速找到商品" },
  ],
  "订单管理": [
    { title: "购物车", desc: "商品加入购物车、数量修改", type: "CRUD", value: "便捷购物体验" },
    { title: "下单流程", desc: "下单、地址选择、优惠券", type: "workflow", value: "流畅下单体验" },
    { title: "订单跟踪", desc: "订单状态实时追踪", type: "CRUD", value: "订单透明化" },
    { title: "退换货", desc: "退货申请、审核、退款流程", type: "workflow", value: "完善售后保障" },
  ],
  "支付管理": [
    { title: "支付集成", desc: "多支付渠道集成", type: "integration", value: "便捷支付" },
    { title: "对账管理", desc: "自动对账、差异处理", type: "workflow", value: "财务准确性" },
    { title: "退款管理", desc: "退款审核与执行", type: "workflow", value: "资金安全" },
  ],
  "营销管理": [
    { title: "优惠券管理", desc: "优惠券创建、发放、核销", type: "CRUD", value: "促销灵活配置" },
    { title: "活动管理", desc: "营销活动策划与执行", type: "CRUD", value: "增长驱动" },
    { title: "推荐系统", desc: "个性化商品推荐", type: "analytics", value: "提升转化率" },
  ],
  "数据分析": [
    { title: "销售分析", desc: "销售额、订单量趋势分析", type: "analytics", value: "销售洞察" },
    { title: "用户分析", desc: "用户画像、行为分析", type: "analytics", value: "用户理解" },
  ],
  "课程管理": [
    { title: "课程创建", desc: "课程信息创建与章节编排", type: "CRUD", value: "丰富课程体系" },
    { title: "资源管理", desc: "视频/文档/测验资源上传管理", type: "CRUD", value: "多媒体教学资源" },
    { title: "课程发布", desc: "课程上架、定价、可见性控制", type: "CRUD", value: "可控课程发布" },
  ],
  "学习管理": [
    { title: "学习进度", desc: "学习进度追踪与记录", type: "CRUD", value: "可视化学情" },
    { title: "作业管理", desc: "作业布置、提交、批改", type: "workflow", value: "完整作业闭环" },
    { title: "考试测评", desc: "在线考试、自动评分", type: "workflow", value: "客观能力评估" },
  ],
  "互动社区": [
    { title: "讨论区", desc: "课程关联讨论、问答", type: "CRUD", value: "学习交流" },
    { title: "学习小组", desc: "学习小组创建与管理", type: "CRUD", value: "协作学习" },
  ],
  "内容管理": [
    { title: "内容创建", desc: "富文本编辑器、多媒体插入", type: "CRUD", value: "高效内容生产" },
    { title: "内容发布", desc: "审核、定时发布、版本管理", type: "workflow", value: "可控内容发布" },
    { title: "内容分类", desc: "分类、标签体系建设", type: "configuration", value: "内容有序组织" },
    { title: "内容搜索", desc: "全文搜索、高级筛选", type: "search", value: "精准内容查找" },
  ],
  "业务流程": [
    { title: "流程定义", desc: "可视化流程设计", type: "configuration", value: "灵活业务配置" },
    { title: "流程执行", desc: "流程触发、流转、结束", type: "workflow", value: "自动化业务流转" },
    { title: "流程监控", desc: "流程状态监控、异常处理", type: "analytics", value: "流程可视化" },
  ],
});

/**
 * 根据 Epic 标题获取 Feature 模板。
 *
 * @param {string} epicTitle
 * @returns {object[]} Feature 模板列表
 */
export function generateFeaturesFromEpic(epic) {
  const templates = EPIC_FEATURE_TEMPLATES[epic.title] || [
    { title: `${epic.title}-基本管理`, desc: `${epic.title}的基本CRUD操作`, type: "CRUD", value: "核心功能覆盖" },
    { title: `${epic.title}-高级配置`, desc: `${epic.title}的高级设置与配置`, type: "configuration", value: "灵活配置能力" },
    { title: `${epic.title}-统计分析`, desc: `${epic.title}相关数据分析`, type: "analytics", value: "数据洞察" },
  ];

  return templates.map(t => createFeature({
    title: t.title,
    description: t.desc,
    epicId: epic.id,
    featureType: t.type || "CRUD",
    userValue: t.value || "",
  }));
}

// ═══════════════════════════════════════════════════════
// Engine 3: User Story Generator (per Feature)
// ═══════════════════════════════════════════════════════

/**
 * 根据 Feature 类型生成 User Stories。
 *
 * @param {object} feature
 * @param {object} epic
 * @param {string[]} roles — 用户角色列表
 * @returns {object[]}
 */
export function generateUserStoriesFromFeature(feature, epic, roles = ["用户", "管理员"]) {
  const stories = [];

  switch (feature.featureType) {
    case "CRUD":
      stories.push(
        { role: roles[0], goal: `浏览${feature.title}列表`, value: `查找所需的${epic.title}信息` },
        { role: roles[0], goal: `查看${feature.title}详情`, value: `了解${epic.title}的完整信息` },
        { role: roles[0], goal: `创建新的${feature.title.replace("管理", "")}`, value: `添加新的${epic.title}条目` },
        { role: roles[0], goal: `编辑已有${feature.title.replace("管理", "")}`, value: `保持${epic.title}信息准确` },
        { role: roles[1] || "管理员", goal: `删除${feature.title.replace("管理", "")}`, value: `清理无效的${epic.title}数据` },
        ...(roles.length > 1 ? [
          { role: roles[1], goal: `批量管理${feature.title}`, value: `高效处理大量${epic.title}数据` },
        ] : []),
      );
      break;

    case "configuration":
      stories.push(
        { role: roles[1] || "管理员", goal: `配置${feature.title}参数`, value: `灵活调整${epic.title}设置` },
        { role: roles[1] || "管理员", goal: `查看${feature.title}配置详情`, value: `了解当前${epic.title}配置状态` },
        { role: roles[1] || "管理员", goal: `重置${feature.title}为默认值`, value: `快速恢复${epic.title}默认设置` },
        { role: roles[0], goal: `查看${feature.title.replace("配置", "")}选项`, value: `了解可用的${epic.title}选项` },
      );
      break;

    case "workflow":
      stories.push(
        { role: roles[0], goal: `发起${feature.title}流程`, value: `启动${epic.title}操作` },
        { role: roles[0], goal: `查看${feature.title}状态`, value: `了解${epic.title}当前进展` },
        { role: roles[1] || "管理员", goal: `审核${feature.title}`, value: `确保${epic.title}合规` },
        { role: roles[0], goal: `处理${feature.title}异常`, value: `及时解决${epic.title}问题` },
      );
      break;

    case "analytics":
      stories.push(
        { role: roles[1] || "管理员", goal: `查看${feature.title}数据概览`, value: `掌握${epic.title}整体状况` },
        { role: roles[1] || "管理员", goal: `按时间维度查看${feature.title}`, value: `分析${epic.title}趋势` },
        { role: roles[1] || "管理员", goal: `导出${feature.title}数据`, value: `对${epic.title}数据进行二次分析` },
        { role: roles[0], goal: `查看个人相关的${feature.title}`, value: `了解自己在${epic.title}中的表现` },
      );
      break;

    case "integration":
      stories.push(
        { role: roles[1] || "管理员", goal: `配置${feature.title}集成`, value: `连接${epic.title}到外部系统` },
        { role: roles[1] || "管理员", goal: `查看${feature.title}日志`, value: `监控${epic.title}运行状态` },
        { role: roles[1] || "管理员", goal: `测试${feature.title}连接`, value: `验证${epic.title}集成是否正常` },
      );
      break;

    case "notification":
      stories.push(
        { role: roles[0], goal: `接收${epic.title}通知`, value: `及时获取${epic.title}重要信息` },
        { role: roles[0], goal: `设置${feature.title}偏好`, value: `个性化${epic.title}通知方式` },
        { role: roles[1] || "管理员", goal: `配置${feature.title}模板`, value: `定制${epic.title}通知内容` },
      );
      break;

    case "search":
      stories.push(
        { role: roles[0], goal: `搜索${epic.title}内容`, value: `快速找到所需的${epic.title}` },
        { role: roles[0], goal: `筛选${feature.title}结果`, value: `精准定位${epic.title}目标` },
        { role: roles[0], goal: `排序${feature.title}结果`, value: `按重要性查看${epic.title}` },
      );
      break;

    default:
      stories.push(
        { role: roles[0], goal: `使用${feature.title}功能`, value: `满足${epic.title}业务需求` },
        { role: roles[1] || "管理员", goal: `管理${feature.title}`, value: `维护${epic.title}正常运行` },
      );
  }

  // Assign priorities
  return stories.map((s, i) => {
    const priority = i === 0 ? STORY_PRIORITY.MUST_HAVE
      : i < 3 ? STORY_PRIORITY.SHOULD_HAVE
      : STORY_PRIORITY.COULD_HAVE;
    return createUserStory({
      role: s.role,
      goal: s.goal,
      value: s.value,
      featureId: feature.id,
      epicId: feature.epicId,
      priority,
      storyPoints: priority === STORY_PRIORITY.MUST_HAVE ? 3 : priority === STORY_PRIORITY.SHOULD_HAVE ? 2 : 1,
    });
  });
}

// ═══════════════════════════════════════════════════════
// Engine 4: Acceptance Criteria Generator (per Story)
// ═══════════════════════════════════════════════════════

/**
 * 根据 User Story 生成 Acceptance Criteria。
 *
 * @param {object} story
 * @returns {object[]}
 */
export function generateAcceptanceCriteriaForStory(story) {
  const goal = story.goal || "";
  const acs = [];

  // Normal flow
  acs.push({
    scenario: "正常流程",
    given: `${story.role}已登录系统`,
    when: `${story.role}执行"${goal}"操作`,
    then: `系统成功完成操作并显示结果`,
  });

  acs.push({
    scenario: "数据展示",
    given: `系统中存在相关数据`,
    when: `${story.role}进入相应页面`,
    then: `系统正确展示所有相关数据`,
  });

  // Edge cases
  acs.push({
    scenario: "空数据",
    given: `系统中不存在相关数据`,
    when: `${story.role}进入相应页面`,
    then: `系统显示友好的空状态提示`,
  });

  acs.push({
    scenario: "数据验证",
    given: `${story.role}准备提交信息`,
    when: `${story.role}提交的数据不符合要求`,
    then: `系统显示明确的验证错误提示`,
  });

  // At least 3 more for richer stories
  acs.push({
    scenario: "权限控制",
    given: `一个没有相应权限的用户`,
    when: `尝试执行"${goal}"操作`,
    then: `系统拒绝访问并提示权限不足`,
  });

  acs.push({
    scenario: "并发处理",
    given: `多个用户同时操作相同数据`,
    when: `系统处理并发请求`,
    then: `数据保持一致，无丢失或覆盖`,
  });

  // Story-specific ACs
  if (goal.includes("创建") || goal.includes("新增") || goal.includes("添加")) {
    acs.push({
      scenario: "重复创建",
      given: `系统中已存在相同数据`,
      when: `${story.role}尝试创建重复条目`,
      then: `系统提示数据已存在，阻止重复创建`,
    });
  }

  if (goal.includes("删除")) {
    acs.push({
      scenario: "删除确认",
      given: `${story.role}触发删除操作`,
      when: `系统弹出确认对话框`,
      then: `${story.role}确认后系统执行删除，取消后不执行`,
    });
    acs.push({
      scenario: "关联数据删除",
      given: `要删除的数据与其他数据有关联`,
      when: `${story.role}执行删除`,
      then: `系统提示关联数据影响，提供安全的删除选项`,
    });
  }

  if (goal.includes("搜索") || goal.includes("查找") || goal.includes("检索")) {
    acs.push({
      scenario: "搜索结果",
      given: `系统中存在匹配和不匹配的数据`,
      when: `${story.role}输入搜索关键词`,
      then: `系统仅返回匹配的结果，并按相关度排序`,
    });
    acs.push({
      scenario: "无搜索结果",
      given: `系统中无匹配数据`,
      when: `${story.role}执行搜索`,
      then: `系统显示"未找到匹配结果"并提供搜索建议`,
    });
  }

  if (goal.includes("导出")) {
    acs.push({
      scenario: "大数据量导出",
      given: `需要导出的数据量较大`,
      when: `${story.role}触发导出操作`,
      then: `系统异步处理导出任务，完成后通知${story.role}下载`,
    });
  }

  return acs.map((ac, i) => createAcceptanceCriteria({
    storyId: story.id,
    given: ac.given,
    when: ac.when,
    then: ac.then,
    scenario: ac.scenario,
    order: i + 1,
  }));
}

// ═══════════════════════════════════════════════════════
// Engine 5: Integration Requirements from Category
// ═══════════════════════════════════════════════════════

/**
 * 从产品分类推导集成需求。
 *
 * @param {string} category — 产品分类
 * @returns {object[]}
 */
export function generateIntegrationRequirements(category = "通用") {
  const templates = CATEGORY_INTEGRATION_TEMPLATES[category] || [];
  return templates.map(t => createIntegrationRequirement({
    name: t.name,
    category: t.category,
    description: t.desc,
    necessity: t.necessity || "required",
    providers: t.providers || [],
    dataFlow: [],
  }));
}

// ═══════════════════════════════════════════════════════
// Engine 6: Non-Functional Requirements from Roadmap
// ═══════════════════════════════════════════════════════

/**
 * 生成非功能需求。
 * 从 Roadmap 的 V1/Enterprise/Global 阶段推导 NFR 严格度。
 *
 * @param {object} strategyPackage
 * @returns {object[]}
 */
export function generateNFRs(strategyPackage) {
  const roadmap = strategyPackage?.roadmap || {};
  const phases = roadmap?.phases || [];
  const hasEnterprise = phases.some(p => p.phase === "enterprise" || p.name?.includes("Enterprise"));
  const hasGlobal = phases.some(p => p.phase === "global" || p.name?.includes("Global"));

  const target100k = "支持 100,000 并发用户";
  const target1M = "支持 1,000,000 并发用户";
  const target99_9 = "99.9% 可用性";
  const target99_99 = "99.99% 可用性";

  const nfrs = [
    {
      name: "页面响应时间",
      description: "核心页面必须在可接受时间内响应",
      category: NFR_CATEGORY.PERFORMANCE,
      metric: "P95 响应时间",
      target: "< 500ms",
      measurement: "APM 工具监控",
    },
    {
      name: "API 响应时间",
      description: "核心 API 接口响应时间",
      category: NFR_CATEGORY.PERFORMANCE,
      metric: "P95 API 响应时间",
      target: "< 200ms",
      measurement: "APM 工具监控",
    },
    {
      name: "并发用户支持",
      description: "系统需支持一定规模并发用户",
      category: NFR_CATEGORY.SCALABILITY,
      metric: "并发用户数",
      target: hasGlobal ? target1M : hasEnterprise ? "支持 50,000 并发用户" : target100k,
      measurement: "压力测试",
    },
    {
      name: "系统可用性",
      description: "系统正常运行时间保障",
      category: NFR_CATEGORY.RELIABILITY,
      metric: "可用性 SLA",
      target: hasEnterprise ? target99_99 : target99_9,
      measurement: "监控系统",
    },
    {
      name: "数据安全",
      description: "用户数据传输和存储的加密保护",
      category: NFR_CATEGORY.SECURITY,
      metric: "加密标准",
      target: "TLS 1.3 传输 + AES-256 存储",
      measurement: "安全审计",
    },
    {
      name: "身份认证安全",
      description: "用户身份认证的安全要求",
      category: NFR_CATEGORY.SECURITY,
      metric: "认证安全等级",
      target: "多因素认证 + 密码强度策略",
      measurement: "渗透测试",
    },
    {
      name: "数据备份与恢复",
      description: "数据备份和灾难恢复能力",
      category: NFR_CATEGORY.RELIABILITY,
      metric: "RPO / RTO",
      target: "RPO < 1小时, RTO < 4小时",
      measurement: "灾备演练",
    },
    {
      name: "国际化支持",
      description: "多语言和多区域支持",
      category: NFR_CATEGORY.I18N,
      metric: "支持语言数",
      target: hasGlobal ? "≥ 8 种语言" : "中文 + 英文",
      measurement: "i18n 覆盖率检查",
    },
    {
      name: "日志与监控",
      description: "系统可观测性要求",
      category: NFR_CATEGORY.OBSERVABILITY,
      metric: "日志/指标/链路覆盖",
      target: "全链路追踪 + 核心指标告警",
      measurement: "可观测性审查",
    },
    {
      name: "浏览器兼容性",
      description: "支持的浏览器版本",
      category: NFR_CATEGORY.COMPATIBILITY,
      metric: "浏览器覆盖",
      target: "Chrome/Firefox/Safari/Edge 最新两个大版本",
      measurement: "跨浏览器测试",
    },
  ];

  return nfrs.map(n => createNonFunctionalRequirement(n));
}

// ═══════════════════════════════════════════════════════
// Engine 7: Permission Requirements
// ═══════════════════════════════════════════════════════

/**
 * 从产品分类和目标客户推导权限需求。
 *
 * @param {object} strategyPackage
 * @returns {object}
 */
export function generatePermissionRequirements(strategyPackage) {
  const category = strategyPackage?.metadata?.category || "通用";

  // Default roles
  const roles = [
    { name: ROLE_TYPE.SUPER_ADMIN, description: "系统超级管理员，拥有全部权限", level: 100 },
    { name: ROLE_TYPE.ADMIN, description: "系统管理员，管理用户和系统配置", level: 80 },
    { name: ROLE_TYPE.OPERATOR, description: "运营人员，管理内容和数据分析", level: 60 },
    { name: ROLE_TYPE.USER, description: "普通用户，使用核心功能", level: 40 },
    { name: ROLE_TYPE.GUEST, description: "未登录访客，仅可浏览公开内容", level: 10 },
    { name: ROLE_TYPE.AUDITOR, description: "审计员，查看操作日志和合规报告", level: 50 },
  ];

  // B2B products add org-level roles
  if (category === "企业SaaS" || category === "ERP") {
    roles.push(
      { name: "部门主管", description: "管理部门成员和数据", level: 65 },
      { name: "HR管理员", description: "管理员工信息和权限", level: 70 },
    );
  }

  // Resources
  const resources = ["user", "content", "config", "analytics", "log"];
  if (category.includes("AI")) resources.push("agent", "knowledge", "conversation");
  if (category.includes("电商")) resources.push("product", "order", "payment", "marketing");
  if (category.includes("教育")) resources.push("course", "assignment", "exam");

  // Permissions
  const actions = ["create", "read", "update", "delete", "export", "manage"];
  const permissions = [];
  for (const r of resources) {
    for (const a of actions) {
      permissions.push({ resource: r, action: a, description: `${a} ${r}` });
    }
  }

  // Role-Permission mapping
  const rolePermissions = [
    { role: ROLE_TYPE.SUPER_ADMIN, permissions: ["*"] },
    { role: ROLE_TYPE.ADMIN, permissions: resources.flatMap(r => actions.map(a => `${r}:${a}`)) },
    { role: ROLE_TYPE.OPERATOR, permissions: resources.map(r => `${r}:read`).concat(["content:create", "content:update", "analytics:export"]) },
    { role: ROLE_TYPE.USER, permissions: resources.map(r => `${r}:read`).concat(["content:create"]) },
    { role: ROLE_TYPE.GUEST, permissions: resources.map(r => `${r}:read`) },
    { role: ROLE_TYPE.AUDITOR, permissions: resources.map(r => `${r}:read`).concat(["log:export"]) },
  ];

  return createPermissionRequirement({
    accessModel: ACCESS_MODEL.HYBRID,
    roles,
    permissions,
    rolePermissions,
    resourceTypes: resources,
  });
}

// ═══════════════════════════════════════════════════════
// Engine 8: Business Rules
// ═══════════════════════════════════════════════════════

/**
 * 从产品分类推导业务规则。
 *
 * @param {object} strategyPackage
 * @returns {object[]}
 */
export function generateBusinessRules(strategyPackage) {
  const rules = [
    createBusinessRule({
      name: "用户注册验证",
      description: "新用户注册时必须提供有效邮箱或手机号，并通过验证",
      ruleType: RULE_TYPE.VALIDATION,
      condition: "用户提交注册表单",
      action: "验证邮箱/手机号唯一性，发送验证码",
      exception: "已认证第三方登录可跳过验证",
    }),
    createBusinessRule({
      name: "密码安全策略",
      description: "用户密码必须符合安全强度要求",
      ruleType: RULE_TYPE.CONSTRAINT,
      condition: "用户设置或修改密码",
      action: "校验密码长度 ≥ 8，必须包含大小写字母和数字",
      exception: "第三方登录无需密码",
    }),
    createBusinessRule({
      name: "登录失败限制",
      description: "连续登录失败后锁定账户",
      ruleType: RULE_TYPE.CONSTRAINT,
      condition: "用户连续 5 次登录失败",
      action: "锁定账户 30 分钟",
      exception: "管理员可手动解锁",
    }),
    createBusinessRule({
      name: "数据删除确认",
      description: "关键数据的删除需要二次确认",
      ruleType: RULE_TYPE.PROCESS,
      condition: "用户尝试删除关键数据",
      action: "弹出二次确认对话框",
      exception: "系统定期清理过期数据无需确认",
    }),
    createBusinessRule({
      name: "操作审计",
      description: "所有关键操作必须记录审计日志",
      ruleType: RULE_TYPE.PROCESS,
      condition: "用户执行创建/更新/删除操作",
      action: "自动记录操作人、时间、内容、IP",
      exception: "只读操作不记录",
    }),
    createBusinessRule({
      name: "审批流程",
      description: "关键业务变更需要上级审批",
      ruleType: RULE_TYPE.APPROVAL,
      condition: "用户提交关键业务变更",
      action: "路由到上级审批人，审批通过后生效",
      exception: "紧急情况下超级管理员可跳过审批",
    }),
    createBusinessRule({
      name: "数据状态流转",
      description: "业务数据的状态变更必须按预定义路径",
      ruleType: RULE_TYPE.STATE_MACHINE,
      condition: "用户触发业务数据状态变更",
      action: "验证状态跳转是否在允许路径中",
      exception: "管理员可执行强制状态跳转（需记录原因）",
    }),
  ];

  return rules;
}

// ═══════════════════════════════════════════════════════
// Engine 9: Data Requirements
// ═══════════════════════════════════════════════════════

/**
 * 从 Epics 列表推导数据需求。
 * 禁止设计数据库，只定义数据实体需求（业务视角）。
 *
 * @param {object[]} epics
 * @param {object} strategyPackage
 * @returns {object[]}
 */
export function generateDataRequirements(epics, strategyPackage) {
  const dataReqs = [];

  // 用户数据（所有产品都有）
  dataReqs.push(createDataRequirement({
    entityName: "用户 (User)",
    description: "系统用户的基本信息，包括身份认证和档案信息",
    requiredFields: ["用户名/邮箱", "密码/认证凭据", "昵称", "头像", "注册时间", "账户状态"],
    relationships: ["用户 → 角色（多对多）", "用户 → 操作日志（一对多）"],
    dataClassification: DATA_CLASSIFICATION.PII,
    lifecycle: [DATA_LIFECYCLE.CREATE, DATA_LIFECYCLE.READ, DATA_LIFECYCLE.UPDATE, DATA_LIFECYCLE.DELETE],
    owner: "用户自己 + 系统管理员",
    complianceReqs: ["GDPR 数据删除权", "个人信息保护法", "数据加密存储"],
  }));

  // 根据 Epics 动态生成
  for (const epic of epics) {
    const title = epic.title;
    if (title.includes("用户") || title.includes("权限")) {
      dataReqs.push(createDataRequirement({
        entityName: "角色与权限 (Role & Permission)",
        description: "定义用户角色和权限分配关系",
        requiredFields: ["角色名称", "权限列表", "角色等级", "创建时间"],
        relationships: ["角色 → 用户（多对多）", "角色 → 权限（多对多）"],
        dataClassification: DATA_CLASSIFICATION.INTERNAL,
        lifecycle: [DATA_LIFECYCLE.CREATE, DATA_LIFECYCLE.READ, DATA_LIFECYCLE.UPDATE, DATA_LIFECYCLE.DELETE],
        owner: "系统管理员",
        complianceReqs: ["权限变更审计日志"],
      }));
    } else if (title.includes("内容") || title.includes("知识") || title.includes("课程")) {
      const entityLabel = title.replace("管理", "");
      dataReqs.push(createDataRequirement({
        entityName: `${entityLabel} (${entityLabel})`,
        description: `${entityLabel}的核心数据结构`,
        requiredFields: ["标题", "内容/描述", "创建者", "创建时间", "状态", "版本号"],
        relationships: [`${entityLabel} → 用户（多对一）`, `${entityLabel} → 分类/标签（多对多）`],
        dataClassification: DATA_CLASSIFICATION.INTERNAL,
        lifecycle: [DATA_LIFECYCLE.CREATE, DATA_LIFECYCLE.READ, DATA_LIFECYCLE.UPDATE, DATA_LIFECYCLE.DELETE, DATA_LIFECYCLE.ARCHIVE],
        owner: `内容创建者 + ${entityLabel}管理员`,
        complianceReqs: ["内容合规审核", "版本历史保留 90 天"],
      }));
    } else if (title.includes("对话")) {
      dataReqs.push(createDataRequirement({
        entityName: "对话记录 (Conversation)",
        description: "AI 对话的会话和消息记录",
        requiredFields: ["会话ID", "用户ID", "消息内容", "消息角色(AI/用户)", "时间戳", "Token 消耗"],
        relationships: ["对话 → 用户（多对一）", "消息 → 会话（多对一）"],
        dataClassification: DATA_CLASSIFICATION.CONFIDENTIAL,
        lifecycle: [DATA_LIFECYCLE.CREATE, DATA_LIFECYCLE.READ, DATA_LIFECYCLE.ARCHIVE, DATA_LIFECYCLE.PURGE],
        owner: "用户 + 系统管理员",
        complianceReqs: ["对话内容脱敏", "用户可请求删除历史", "对话数据保留 ≤ 180 天"],
      }));
    } else if (title.includes("订单")) {
      dataReqs.push(createDataRequirement({
        entityName: "订单 (Order)",
        description: "交易订单的完整信息",
        requiredFields: ["订单编号", "用户ID", "商品/服务信息", "金额", "支付状态", "订单状态", "创建时间"],
        relationships: ["订单 → 用户（多对一）", "订单 → 支付记录（一对一）", "订单 → 商品（多对多）"],
        dataClassification: DATA_CLASSIFICATION.CONFIDENTIAL,
        lifecycle: [DATA_LIFECYCLE.CREATE, DATA_LIFECYCLE.READ, DATA_LIFECYCLE.UPDATE, DATA_LIFECYCLE.ARCHIVE],
        owner: "用户 + 财务",
        complianceReqs: ["支付信息加密", "财务数据保留 ≥ 5 年", "PCI DSS 合规"],
      }));
    } else if (title.includes("分析") || title.includes("报表")) {
      dataReqs.push(createDataRequirement({
        entityName: "分析数据 (Analytics)",
        description: "业务分析指标和数据快照",
        requiredFields: ["指标名称", "指标值", "统计时间", "维度标签"],
        relationships: [],
        dataClassification: DATA_CLASSIFICATION.INTERNAL,
        lifecycle: [DATA_LIFECYCLE.CREATE, DATA_LIFECYCLE.READ, DATA_LIFECYCLE.ARCHIVE],
        owner: "运营团队",
        complianceReqs: ["数据脱敏", "聚合数据不包含 PII"],
      }));
    }
  }

  // 操作日志（所有产品都需要）
  if (!dataReqs.some(d => d.entityName.includes("日志"))) {
    dataReqs.push(createDataRequirement({
      entityName: "操作日志 (Audit Log)",
      description: "用户关键操作的审计记录",
      requiredFields: ["操作人", "操作类型", "操作对象", "操作时间", "IP地址", "操作结果"],
      relationships: ["操作日志 → 用户（多对一）"],
      dataClassification: DATA_CLASSIFICATION.INTERNAL,
      lifecycle: [DATA_LIFECYCLE.CREATE, DATA_LIFECYCLE.READ, DATA_LIFECYCLE.ARCHIVE, DATA_LIFECYCLE.PURGE],
      owner: "系统管理员",
      complianceReqs: ["审计日志保留 ≥ 180 天", "日志不可篡改"],
    }));
  }

  return dataReqs;
}

// ═══════════════════════════════════════════════════════
// Engine 10: Constraints
// ═══════════════════════════════════════════════════════

export function generateConstraints(strategyPackage) {
  const roadmap = strategyPackage?.roadmap || {};
  let _ctSeq2 = 0;
  return [
    {
      name: "MVP 时间约束",
      description: `MVP 版本需要在 ${roadmap.totalDurationMonths || 6} 个月内交付`,
      constraintType: "时间约束",
      impact: "功能范围需要按 MoSCoW 严格裁剪",
      mitigation: "优先实现 Must Have 功能，Should Have 可延后到 V1",
    },
    {
      name: "预算约束",
      description: `项目预算限制：$${(roadmap.totalBudget || 0).toLocaleString()}`,
      constraintType: "预算约束",
      impact: "需要控制第三方服务成本和技术栈选择",
      mitigation: "优先选择开源方案和按量付费模式",
    },
    {
      name: "技术约束",
      description: "目标平台和浏览器兼容性要求",
      constraintType: "技术约束",
      impact: "技术选型需考虑跨平台兼容性",
      mitigation: "使用成熟的跨平台技术方案",
    },
    {
      name: "合规约束",
      description: "数据隐私和安全合规要求",
      constraintType: "合规约束",
      impact: "数据处理和存储需满足 GDPR/个人信息保护法",
      mitigation: "实施数据分类分级管理和隐私设计原则",
    },
  ].map(c => ({
    id: `ct-${++_ctSeq2}`,
    name: c.name,
    description: c.description,
    constraintType: c.constraintType,
    impact: c.impact,
    mitigation: c.mitigation,
    metadata: {},
    createdAt: new Date().toISOString(),
  }));
}

// ═══════════════════════════════════════════════════════
// Master: Full Strategy → Requirement Conversion
// ═══════════════════════════════════════════════════════

/**
 * 一键转换：Product Strategy Package → Complete Requirements。
 *
 * @param {object} strategyPackage — SF-01 产出的 Strategy Package
 * @returns {object} { epics, features, userStories, acceptanceCriteria, ... }
 */
export function convertStrategyToRequirements(strategyPackage) {
  // 1. Epics
  const epics = generateEpicsFromStrategy(strategyPackage);

  // 2. Features (per Epic)
  const features = [];
  for (const epic of epics) {
    const epicFeatures = generateFeaturesFromEpic(epic);
    features.push(...epicFeatures);
  }

  // 3. User Stories (per Feature)
  const userStories = [];
  for (const feature of features) {
    const epic = epics.find(e => e.id === feature.epicId);
    const epicStories = generateUserStoriesFromFeature(feature, epic || { title: "通用" });
    userStories.push(...epicStories);
  }

  // 4. Acceptance Criteria (per Story)
  const acceptanceCriteria = [];
  for (const story of userStories) {
    const acs = generateAcceptanceCriteriaForStory(story);
    acceptanceCriteria.push(...acs);
  }

  // 5. Business Rules
  const businessRules = generateBusinessRules(strategyPackage);

  // 6. NFRs
  const nonFunctionalReqs = generateNFRs(strategyPackage);

  // 7. Permissions
  const permissionReqs = generatePermissionRequirements(strategyPackage);

  // 8. Integration Requirements
  const category = strategyPackage?.metadata?.category || "通用";
  const integrationReqs = generateIntegrationRequirements(category);

  // 9. Data Requirements
  const dataReqs = generateDataRequirements(epics, strategyPackage);

  return {
    epics,
    features,
    userStories,
    acceptanceCriteria,
    businessRules,
    nonFunctionalReqs,
    permissionReqs,
    integrationReqs,
    dataReqs,
    summary: {
      epicCount: epics.length,
      featureCount: features.length,
      storyCount: userStories.length,
      acCount: acceptanceCriteria.length,
      businessRuleCount: businessRules.length,
      nfrCount: nonFunctionalReqs.length,
      integrationReqCount: integrationReqs.length,
      dataReqCount: dataReqs.length,
    },
  };
}
