/**
 * SF-01 Product Strategy Factory — Domain Model
 *
 * Part A：统一产品战略域模型。
 *
 * 定义产品战略分析所需的全部类型：
 *   ProductIdea / ProductVision / TargetMarket / TargetCustomer
 *   ProblemStatement / ValueProposition / CompetitiveLandscape
 *   BusinessModel / RevenueModel / GoToMarketStrategy
 *   RiskAssessment / SuccessMetric / Roadmap
 *
 * 设计原则：
 *   - 纯类型定义 + 工厂函数，无副作用
 *   - 不可变创建模式
 *   - 所有类型通过 metadata 支持扩展
 *   - 与 PR-35/PR-36 类型系统兼容
 *   - 零外部依赖
 *
 * @module sf-01-product-strategy/domain-model
 * @since SF-01
 */

// ═══════════════════════════════════════════════════════
// 1. ProductIdea — 产品创意
// ═══════════════════════════════════════════════════════

let _piSeq = 0;

/**
 * 产品创意 — 最原始的输入。
 *
 * 一句话产品想法 + AI 扩展的结构化分析。
 *
 * @param {object} p
 * @param {string} p.raw              — 用户原始输入（自然语言）
 * @param {string[]} [p.keywords=[]]   — 提取的关键词
 * @param {string} [p.category=""]     — 产品分类
 * @param {string} [p.subCategory=""]  — 子分类
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createProductIdea({ raw, keywords = [], category = "", subCategory = "", metadata = {} }) {
  if (!raw) throw new TypeError("ProductIdea.raw is required");
  return {
    id: `pi-${++_piSeq}`,
    raw,
    keywords: [...keywords],
    category,
    subCategory,
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 2. ProductVision — 产品愿景
// ═══════════════════════════════════════════════════════

let _pvSeq = 0;

/**
 * 产品愿景 — 产品存在的终极理由。
 *
 * @param {object} p
 * @param {string} p.vision           — 愿景陈述（5-10 年后世界因产品而怎样）
 * @param {string} p.mission          — 使命陈述（我们每天做什么来实现愿景）
 * @param {string} p.northStarMetric  — 北极星指标（衡量产品价值的单一指标）
 * @param {string[]} p.coreValues     — 核心价值主张列表
 * @param {string} [p.longTermGoal=""] — 长期目标（3-5 年）
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createProductVision({ vision, mission, northStarMetric, coreValues = [], longTermGoal = "", metadata = {} }) {
  if (!vision) throw new TypeError("ProductVision.vision is required");
  if (!mission) throw new TypeError("ProductVision.mission is required");
  return {
    id: `pv-${++_pvSeq}`,
    vision,
    mission,
    northStarMetric,
    coreValues: [...coreValues],
    longTermGoal,
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 3. TargetMarket — 目标市场
// ═══════════════════════════════════════════════════════

let _tmSeq = 0;

/**
 * 目标市场 — 产品面向的市场定义。
 *
 * @param {object} p
 * @param {string} [p.id]
 * @param {string} p.name            — 市场名称
 * @param {number} p.tam              — TAM (Total Addressable Market) 美元
 * @param {number} p.sam              — SAM (Serviceable Available Market) 美元
 * @param {number} p.som              — SOM (Serviceable Obtainable Market) 美元
 * @param {number} [p.growthRate=0]   — 年增长率 (%)
 * @param {string} [p.concentration=""] — 市场集中度 (fragmented/moderate/concentrated/oligopoly/monopoly)
 * @param {string} [p.maturity=""]     — 市场成熟度 (emerging/growing/mature/declining)
 * @param {string[]} [p.trends=[]]     — 市场趋势
 * @param {string[]} [p.regions=[]]    — 目标区域
 * @param {number} [p.aiImpact=0]      — AI 影响程度 (0-100)
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createTargetMarket({
  id, name, tam, sam, som,
  growthRate = 0, concentration = "", maturity = "",
  trends = [], regions = [], aiImpact = 0, metadata = {},
}) {
  if (!name) throw new TypeError("TargetMarket.name is required");
  return {
    id: id || `tm-${++_tmSeq}`,
    name,
    tam: Math.max(0, Math.round(tam)),
    sam: Math.max(0, Math.round(sam)),
    som: Math.max(0, Math.round(som)),
    growthRate,
    concentration,
    maturity,
    trends: [...trends],
    regions: [...regions],
    aiImpact: Math.max(0, Math.min(100, Math.round(aiImpact))),
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 4. TargetCustomer — 目标客户
// ═══════════════════════════════════════════════════════

let _tcSeq = 0;

/**
 * 目标客户 — 产品的理想用户画像。
 *
 * @param {object} p
 * @param {string} [p.id]
 * @param {string} p.segment           — 客户细分名称
 * @param {string} [p.persona=""]       — 客户画像描述
 * @param {string[]} [p.painPoints=[]]  — 痛点列表
 * @param {string[]} [p.needs=[]]       — 需求列表
 * @param {string[]} [p.jobs=[]]        — Jobs-to-be-done
 * @param {number} [p.willingnessToPay=0] — 付费意愿 (0-100)
 * @param {number} [p.marketSize=0]     — 该细分市场规模（人/企业数）
 * @param {string[]} [p.alternatives=[]] — 替代方案
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createTargetCustomer({
  id, segment, persona = "",
  painPoints = [], needs = [], jobs = [],
  willingnessToPay = 0, marketSize = 0, alternatives = [],
  metadata = {},
}) {
  if (!segment) throw new TypeError("TargetCustomer.segment is required");
  return {
    id: id || `tc-${++_tcSeq}`,
    segment,
    persona,
    painPoints: [...painPoints],
    needs: [...needs],
    jobs: [...jobs],
    willingnessToPay: Math.max(0, Math.min(100, Math.round(willingnessToPay))),
    marketSize,
    alternatives: [...alternatives],
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 5. ProblemStatement — 问题陈述
// ═══════════════════════════════════════════════════════

let _psSeq = 0;

/**
 * 问题陈述 — 产品要解决的核心问题。
 *
 * 格式：为 [谁] 解决 [什么问题]，因为 [原因]。
 *
 * @param {object} p
 * @param {string} p.who              — 为谁
 * @param {string} p.what             — 什么问题
 * @param {string} p.why              — 为什么重要
 * @param {number} [p.severity=50]    — 问题严重程度 (0-100)
 * @param {number} [p.frequency=50]   — 问题发生频率 (0-100)
 * @param {string[]} [p.evidence=[]]  — 佐证数据
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createProblemStatement({ who, what, why, severity = 50, frequency = 50, evidence = [], metadata = {} }) {
  if (!who || !what) throw new TypeError("ProblemStatement requires who and what");
  return {
    id: `ps-${++_psSeq}`,
    who, what, why,
    severity: Math.max(0, Math.min(100, Math.round(severity))),
    frequency: Math.max(0, Math.min(100, Math.round(frequency))),
    evidence: [...evidence],
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 6. ValueProposition — 价值主张
// ═══════════════════════════════════════════════════════

let _vpSeq = 0;

/**
 * 价值主张 — 产品为用户创造的价值。
 *
 * @param {object} p
 * @param {string} p.statement          — 一句话价值主张
 * @param {string[]} p.benefits         — 核心利益点
 * @param {string[]} p.differentiators  — 差异化优势
 * @param {number} [p.valueScore=50]    — 价值评分 (0-100)
 * @param {number} [p.uniqueness=50]    — 独特性 (0-100)
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createValueProposition({ statement, benefits = [], differentiators = [], valueScore = 50, uniqueness = 50, metadata = {} }) {
  if (!statement) throw new TypeError("ValueProposition.statement is required");
  return {
    id: `vp-${++_vpSeq}`,
    statement,
    benefits: [...benefits],
    differentiators: [...differentiators],
    valueScore: Math.max(0, Math.min(100, Math.round(valueScore))),
    uniqueness: Math.max(0, Math.min(100, Math.round(uniqueness))),
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 7. CompetitiveLandscape — 竞争格局
// ═══════════════════════════════════════════════════════

let _clSeq = 0;

/**
 * 竞争格局 — 市场参与者的全景分析。
 *
 * @param {object} p
 * @param {object[]} p.directCompetitors     — 直接竞品列表
 * @param {object[]} [p.indirectCompetitors=[]] — 间接竞品列表
 * @param {string[]} [p.substitutes=[]]       — 替代方案
 * @param {number} [p.competitionIntensity=50] — 竞争激烈度 (0-100)
 * @param {number} [p.barrierToEntry=50]       — 进入壁垒 (0-100)
 * @param {number} [p.moatStrength=50]         — 护城河强度 (0-100)
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createCompetitiveLandscape({
  directCompetitors = [], indirectCompetitors = [], substitutes = [],
  competitionIntensity = 50, barrierToEntry = 50, moatStrength = 50,
  metadata = {},
}) {
  if (directCompetitors.length === 0 && indirectCompetitors.length === 0 && substitutes.length === 0) {
    // 允许初始创建时为空（后续追加）
  }
  return {
    id: `cl-${++_clSeq}`,
    directCompetitors: [...directCompetitors],
    indirectCompetitors: [...indirectCompetitors],
    substitutes: [...substitutes],
    competitionIntensity: Math.max(0, Math.min(100, Math.round(competitionIntensity))),
    barrierToEntry: Math.max(0, Math.min(100, Math.round(barrierToEntry))),
    moatStrength: Math.max(0, Math.min(100, Math.round(moatStrength))),
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 8. BusinessModel — 商业模式
// ═══════════════════════════════════════════════════════

export const BUSINESS_MODEL_TYPE = Object.freeze({
  SAAS:         "saas",
  LICENSE:      "license",
  SUBSCRIPTION: "subscription",
  FREEMIUM:     "freemium",
  MARKETPLACE:  "marketplace",
  ENTERPRISE:   "enterprise",
  HYBRID:       "hybrid",
});

let _bmSeq = 0;

/**
 * 商业模式 — 产品如何创造、交付和获取价值。
 *
 * @param {object} p
 * @param {string} p.type                — BUSINESS_MODEL_TYPE
 * @param {string} [p.description=""]     — 商业模式描述
 * @param {object[]} [p.revenueStreams=[]] — 收入来源列表
 * @param {object[]} [p.costStructure=[]]  — 成本结构列表
 * @param {number} [p.grossMargin=0]       — 毛利率 (%)
 * @param {number} [p.customerLTV=0]       — 客户终身价值
 * @param {number} [p.customerCAC=0]       — 客户获取成本
 * @param {number} [p.paybackMonths=0]     — 回本周期（月）
 * @param {number} [p.breakevenMonths=0]   — 盈亏平衡（月）
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createBusinessModel({
  type, description = "",
  revenueStreams = [], costStructure = [],
  grossMargin = 0, customerLTV = 0, customerCAC = 0,
  paybackMonths = 0, breakevenMonths = 0,
  metadata = {},
}) {
  if (!type || !BUSINESS_MODEL_TYPE[type.toUpperCase()]) {
    throw new TypeError(`Invalid business model type: ${type}`);
  }
  return {
    id: `bm-${++_bmSeq}`,
    type,
    description,
    revenueStreams: [...revenueStreams],
    costStructure: [...costStructure],
    grossMargin: Math.round(grossMargin),
    customerLTV: Math.round(customerLTV),
    customerCAC: Math.round(customerCAC),
    ltvCacRatio: customerCAC > 0 ? Number((customerLTV / customerCAC).toFixed(1)) : 0,
    paybackMonths,
    breakevenMonths,
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 9. RevenueModel — 收入模型
// ═══════════════════════════════════════════════════════

let _rmSeq = 0;

/**
 * 收入模型 — 产品的货币化策略。
 *
 * @param {object} p
 * @param {string} p.primaryModel       — 主要收入模式
 * @param {string[]} [p.streams=[]]      — 所有收入流
 * @param {number} [p.arpu=0]            — 每用户平均收入（年）
 * @param {number} [p.estimatedMRR=0]    — 预估月经常性收入
 * @param {number} [p.estimatedARR=0]    — 预估年经常性收入
 * @param {number} [p.year1Revenue=0]    — 第一年预估收入
 * @param {number} [p.year3Revenue=0]    — 第三年预估收入
 * @param {number} [p.year5Revenue=0]    — 第五年预估收入
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createRevenueModel({
  primaryModel, streams = [],
  arpu = 0, estimatedMRR = 0, estimatedARR = 0,
  year1Revenue = 0, year3Revenue = 0, year5Revenue = 0,
  metadata = {},
}) {
  if (!primaryModel) throw new TypeError("RevenueModel.primaryModel is required");
  return {
    id: `rm-${++_rmSeq}`,
    primaryModel,
    streams: [...streams],
    arpu: Math.round(arpu),
    estimatedMRR: Math.round(estimatedMRR),
    estimatedARR: Math.round(estimatedARR),
    year1Revenue: Math.round(year1Revenue),
    year3Revenue: Math.round(year3Revenue),
    year5Revenue: Math.round(year5Revenue),
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 10. GoToMarketStrategy — 市场进入策略
// ═══════════════════════════════════════════════════════

let _gsSeq = 0;

/**
 * GTM 策略 — 如何将产品推向市场。
 *
 * @param {object} p
 * @param {string} p.entryStrategy       — 进入策略
 * @param {string[]} [p.channels=[]]      — 渠道策略
 * @param {string[]} [p.acquisitionChannels=[]] — 获客渠道
 * @param {string} [p.coldStartPlan=""]   — 冷启动方案
 * @param {string} [p.brandStrategy=""]   — 品牌策略
 * @param {string} [p.growthModel=""]     — 增长模型
 * @param {number} [p.timeToMarketMonths=0] — 上市时间（月）
 * @param {number} [p.initialBudget=0]    — 初始预算
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createGoToMarketStrategy({
  entryStrategy, channels = [], acquisitionChannels = [],
  coldStartPlan = "", brandStrategy = "", growthModel = "",
  timeToMarketMonths = 0, initialBudget = 0,
  metadata = {},
}) {
  if (!entryStrategy) throw new TypeError("GoToMarketStrategy.entryStrategy is required");
  return {
    id: `gs-${++_gsSeq}`,
    entryStrategy,
    channels: [...channels],
    acquisitionChannels: [...acquisitionChannels],
    coldStartPlan,
    brandStrategy,
    growthModel,
    timeToMarketMonths,
    initialBudget: Math.round(initialBudget),
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 11. RiskAssessment — 风险评估
// ═══════════════════════════════════════════════════════

let _raSeq = 0;

/**
 * 风险评估 — 产品面临的全部风险。
 *
 * 风险等级：critical / high / medium / low
 *
 * @param {object} p
 * @param {object[]} p.risks             — 风险列表 [{name, level, description, mitigation, probability}]
 * @param {number} [p.overallRisk=50]    — 综合风险评分 (0-100, 越高越危险)
 * @param {number} [p.marketRisk=50]     — 市场风险
 * @param {number} [p.techRisk=50]       — 技术风险
 * @param {number} [p.executionRisk=50]  — 执行风险
 * @param {number} [p.competitionRisk=50] — 竞争风险
 * @param {number} [p.financialRisk=50]  — 财务风险
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createRiskAssessment({
  risks = [],
  overallRisk = 50, marketRisk = 50, techRisk = 50,
  executionRisk = 50, competitionRisk = 50, financialRisk = 50,
  metadata = {},
}) {
  return {
    id: `ra-${++_raSeq}`,
    risks: [...risks],
    overallRisk: Math.max(0, Math.min(100, Math.round(overallRisk))),
    breakdown: {
      marketRisk: Math.max(0, Math.min(100, Math.round(marketRisk))),
      techRisk: Math.max(0, Math.min(100, Math.round(techRisk))),
      executionRisk: Math.max(0, Math.min(100, Math.round(executionRisk))),
      competitionRisk: Math.max(0, Math.min(100, Math.round(competitionRisk))),
      financialRisk: Math.max(0, Math.min(100, Math.round(financialRisk))),
    },
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 12. SuccessMetric — 成功指标
// ═══════════════════════════════════════════════════════

let _smSeq = 0;

/**
 * 成功指标 — 衡量产品是否成功的 KPI 体系。
 *
 * @param {object} p
 * @param {string} p.northStar           — 北极星指标
 * @param {object[]} [p.kpis=[]]          — KPI 列表 [{name, target, unit, timeframe}]
 * @param {object[]} [p.milestones=[]]     — 里程碑 [{phase, target, deadline}]
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createSuccessMetric({ northStar, kpis = [], milestones = [], metadata = {} }) {
  if (!northStar) throw new TypeError("SuccessMetric.northStar is required");
  return {
    id: `sm-${++_smSeq}`,
    northStar,
    kpis: [...kpis],
    milestones: [...milestones],
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}

// ═══════════════════════════════════════════════════════
// 13. Roadmap — 产品路线图
// ═══════════════════════════════════════════════════════

export const ROADMAP_PHASE = Object.freeze({
  MVP:           "mvp",
  V1:            "v1",
  V2:            "v2",
  V3:            "v3",
  ENTERPRISE:    "enterprise",
  GLOBALIZATION: "globalization",
});

let _rmapSeq = 0;

/**
 * Roadmap Phase — 单个路线图阶段。
 *
 * @param {object} p
 * @param {string} p.phase              — ROADMAP_PHASE
 * @param {string} p.goal               — 阶段目标
 * @param {string[]} [p.features=[]]     — 核心功能
 * @param {number} [p.durationMonths=3]  — 预计工期（月）
 * @param {number} [p.teamSize=3]        — 团队规模
 * @param {number} [p.budget=0]          — 预算
 * @param {object[]} [p.successCriteria=[]] — 成功标准
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createRoadmapPhase({
  phase, goal, features = [],
  durationMonths = 3, teamSize = 3, budget = 0,
  successCriteria = [], metadata = {},
}) {
  if (!ROADMAP_PHASE[phase.toUpperCase()]) throw new TypeError(`Invalid roadmap phase: ${phase}`);
  return {
    phase,
    goal,
    features: [...features],
    durationMonths,
    teamSize,
    budget: Math.round(budget),
    successCriteria: [...successCriteria],
    metadata: { ...metadata },
  };
}

/**
 * 产品路线图 — 从 MVP 到全球化的完整路径。
 *
 * @param {object} p
 * @param {object[]} p.phases            — RoadmapPhase 列表
 * @param {number} [p.totalDurationMonths=0]
 * @param {number} [p.totalBudget=0]
 * @param {object} [p.metadata={}]
 * @returns {object}
 */
export function createRoadmap({ phases = [], totalDurationMonths = 0, totalBudget = 0, metadata = {} }) {
  return {
    id: `rmap-${++_rmapSeq}`,
    phases: [...phases],
    totalDurationMonths: totalDurationMonths || phases.reduce((s, p) => s + (p.durationMonths || 0), 0),
    totalBudget: totalBudget || phases.reduce((s, p) => s + (p.budget || 0), 0),
    metadata: { ...metadata },
    createdAt: new Date().toISOString(),
  };
}
