/**
 * SF-01 Product Strategy Factory — Business Model Engine
 *
 * Part E：商业模式分析引擎。
 *
 * 支持 7 种商业模式：
 *   SaaS / License / Subscription / Freemium / Marketplace / Enterprise / Hybrid
 *
 * 分析维度：
 *   收入来源 / 成本结构 / 毛利分析 / 现金流分析 / 盈利周期分析 / LTV/CAC
 *
 * @module sf-01-product-strategy/business-model
 * @since SF-01
 */

import { createBusinessModel, createRevenueModel, BUSINESS_MODEL_TYPE } from "./domain-model.mjs";

// ═══════════════════════════════════════════════════════
// 商业模式推荐逻辑
// ═══════════════════════════════════════════════════════

const MODEL_FIT_RULES = [
  { category: /ERP|erp|MES|mes|企业管理/, prefer: "enterprise", score: 90 },
  { category: /AI.*(Agent|平台)|平台.*AI/, prefer: "saas", score: 85 },
  { category: /客服|chatbot|聊天|customer.?service/, prefer: "subscription", score: 80 },
  { category: /CAD|cad|设计|design/, prefer: "license", score: 75 },
  { category: /视频|video|剪辑|edit/, prefer: "freemium", score: 80 },
  { category: /电商|ecommerce|跨境/, prefer: "marketplace", score: 85 },
  { category: /SaaS|saas|云/, prefer: "saas", score: 95 },
];

const MODEL_DESCRIPTIONS = {
  [BUSINESS_MODEL_TYPE.SAAS]: {
    label: "SaaS (Software-as-a-Service)",
    revenue: "按月/年订阅费 + 按用量计费",
    typicalGrossMargin: 75,
    typicalCAC: "$500-$5000",
    typicalPaybackMonths: 12,
  },
  [BUSINESS_MODEL_TYPE.LICENSE]: {
    label: "License (许可授权)",
    revenue: "一次性许可费 + 年度维护费(15-20%)",
    typicalGrossMargin: 85,
    typicalCAC: "$5000-$50000",
    typicalPaybackMonths: 6,
  },
  [BUSINESS_MODEL_TYPE.SUBSCRIPTION]: {
    label: "Subscription (订阅制)",
    revenue: "月/季/年订阅",
    typicalGrossMargin: 70,
    typicalCAC: "$100-$2000",
    typicalPaybackMonths: 8,
  },
  [BUSINESS_MODEL_TYPE.FREEMIUM]: {
    label: "Freemium (免费增值)",
    revenue: "免费版吸引用户 → 付费版转化 (2-5% 转化率)",
    typicalGrossMargin: 80,
    typicalCAC: "$50-$500",
    typicalPaybackMonths: 18,
  },
  [BUSINESS_MODEL_TYPE.MARKETPLACE]: {
    label: "Marketplace (平台市场)",
    revenue: "交易抽佣 (5-30%) + 增值服务",
    typicalGrossMargin: 60,
    typicalCAC: "$200-$2000",
    typicalPaybackMonths: 24,
  },
  [BUSINESS_MODEL_TYPE.ENTERPRISE]: {
    label: "Enterprise (企业定制)",
    revenue: "项目制收费 + 年度维护 + 增值模块",
    typicalGrossMargin: 50,
    typicalCAC: "$10000-$100000",
    typicalPaybackMonths: 3,
  },
  [BUSINESS_MODEL_TYPE.HYBRID]: {
    label: "Hybrid (混合模式)",
    revenue: "SaaS 底座 + License 私有部署 + 增值服务",
    typicalGrossMargin: 65,
    typicalCAC: "$1000-$10000",
    typicalPaybackMonths: 12,
  },
};

// ═══════════════════════════════════════════════════════
// 主入口
// ═══════════════════════════════════════════════════════

/**
 * 分析并推荐商业模式。
 *
 * @param {object} ideaAnalysis — IdeaAnalysisResult
 * @param {object} [marketAnalysis] — MarketAnalysisResult
 * @returns {object} BusinessModelResult
 */
export function analyzeBusinessModel(ideaAnalysis, marketAnalysis) {
  const category = ideaAnalysis?.category || "unknown";

  // 1. 推荐最佳商业模式
  const recommendation = _recommendModel(category, ideaAnalysis, marketAnalysis);

  // 2. 创建 BusinessModel
  const model = createBusinessModel({
    type: recommendation.primary,
    description: MODEL_DESCRIPTIONS[recommendation.primary]?.label || "",
    revenueStreams: recommendation.revenueStreams,
    costStructure: recommendation.costStructure,
    grossMargin: MODEL_DESCRIPTIONS[recommendation.primary]?.typicalGrossMargin || 60,
    customerLTV: recommendation.estimatedLTV,
    customerCAC: recommendation.estimatedCAC,
    paybackMonths: MODEL_DESCRIPTIONS[recommendation.primary]?.typicalPaybackMonths || 12,
    breakevenMonths: recommendation.breakevenMonths,
  });

  // 3. 创建 RevenueModel
  const tam = ideaAnalysis?.market?.tam || 1_000_000_000;
  const revenue = createRevenueModel({
    primaryModel: recommendation.primary,
    streams: recommendation.revenueStreams.map(s => s.name),
    arpu: recommendation.estimatedARPU,
    estimatedMRR: recommendation.estimatedMRR,
    estimatedARR: recommendation.estimatedARR,
    year1Revenue: Math.round(tam * 0.0001),
    year3Revenue: Math.round(tam * 0.001),
    year5Revenue: Math.round(tam * 0.005),
  });

  // 4. 比较模型
  const alternatives = Object.entries(MODEL_DESCRIPTIONS)
    .filter(([type]) => type !== recommendation.primary)
    .map(([type, desc]) => ({
      type,
      label: desc.label,
      fitScore: _modelFitScore(type, category, ideaAnalysis),
      pros: _modelPros(type),
      cons: _modelCons(type),
    }))
    .sort((a, b) => b.fitScore - a.fitScore)
    .slice(0, 3);

  // 5. 现金流预估
  const cashflow = _estimateCashflow(recommendation);

  // 6. 生成报告
  const report = _generateReport(model, revenue, recommendation, alternatives, cashflow);

  return {
    model,
    revenue,
    recommendation,
    alternatives,
    cashflow,
    report,
  };
}

// ═══════════════════════════════════════════════════════
// 推荐逻辑
// ═══════════════════════════════════════════════════════

function _recommendModel(category, ideaAnalysis, marketAnalysis) {
  const raw = ideaAnalysis?.raw || "";
  let bestType = "saas";
  let bestScore = 0;

  for (const rule of MODEL_FIT_RULES) {
    const pattern = rule.category || rule.pattern;
    if (pattern.test(raw) || pattern.test(category || "")) {
      if (rule.score > bestScore) {
        bestScore = rule.score;
        bestType = rule.prefer;
      }
    }
  }

  // 根据 AI 影响调整
  if (ideaAnalysis?.market?.aiImpact > 70) {
    bestType = "saas"; // AI 产品天然适合 SaaS
  }

  const modelDesc = MODEL_DESCRIPTIONS[bestType] || MODEL_DESCRIPTIONS[BUSINESS_MODEL_TYPE.SAAS];

  return {
    primary: bestType,
    score: bestScore,
    revenueStreams: _revenueStreamsForType(bestType, ideaAnalysis),
    costStructure: _costStructureForType(bestType),
    estimatedLTV: _estimateLTV(bestType, ideaAnalysis),
    estimatedCAC: _estimateCAC(bestType),
    estimatedARPU: _estimateARPU(bestType, ideaAnalysis),
    estimatedMRR: _estimateMRR(bestType, ideaAnalysis),
    estimatedARR: _estimateARR(bestType, ideaAnalysis),
    breakevenMonths: modelDesc.typicalPaybackMonths || 12,
  };
}

function _revenueStreamsForType(type, ideaAnalysis) {
  switch (type) {
    case "saas": return [
      { name: "月度订阅", percentage: 70 },
      { name: "年度订阅", percentage: 20 },
      { name: "增值服务", percentage: 10 },
    ];
    case "license": return [
      { name: "一次性许可费", percentage: 60 },
      { name: "年度维护费(15-20%)", percentage: 30 },
      { name: "定制开发", percentage: 10 },
    ];
    case "subscription": return [
      { name: "月度订阅", percentage: 50 },
      { name: "年度订阅(折扣)", percentage: 35 },
      { name: "高级功能", percentage: 15 },
    ];
    case "freemium": return [
      { name: "免费版(获客)", percentage: 0 },
      { name: "Pro 版转化(~3%)", percentage: 60 },
      { name: "Enterprise 版", percentage: 40 },
    ];
    case "marketplace": return [
      { name: "交易抽佣", percentage: 70 },
      { name: "广告/推广", percentage: 15 },
      { name: "增值工具", percentage: 15 },
    ];
    case "enterprise": return [
      { name: "项目制收费", percentage: 60 },
      { name: "年度维护", percentage: 25 },
      { name: "扩展模块", percentage: 15 },
    ];
    case "hybrid": return [
      { name: "SaaS 订阅", percentage: 50 },
      { name: "私有部署 License", percentage: 30 },
      { name: "咨询服务", percentage: 20 },
    ];
    default: return [{ name: "订阅收入", percentage: 100 }];
  }
}

function _costStructureForType(type) {
  return [
    { category: "研发成本", percentage: 40 },
    { category: "销售与市场", percentage: 30 },
    { category: "基础设施", percentage: 15 },
    { category: "管理与运营", percentage: 15 },
  ];
}

function _estimateLTV(type, ideaAnalysis) {
  const baseLTV = {
    saas: 50000, license: 200000, subscription: 30000, freemium: 20000,
    marketplace: 15000, enterprise: 500000, hybrid: 80000,
  };
  const willingness = ideaAnalysis?.scores?.willingnessToPay || 50;
  return Math.round((baseLTV[type] || 50000) * (willingness / 50));
}

function _estimateCAC(type) {
  const baseCAC = {
    saas: 5000, license: 50000, subscription: 2000, freemium: 500,
    marketplace: 2000, enterprise: 100000, hybrid: 10000,
  };
  return baseCAC[type] || 5000;
}

function _estimateARPU(type, ideaAnalysis) {
  const arpu = {
    saas: 5000, license: 50000, subscription: 3000, freemium: 1200,
    marketplace: 2000, enterprise: 200000, hybrid: 10000,
  };
  return arpu[type] || 5000;
}

function _estimateMRR(type, ideaAnalysis) {
  const tam = ideaAnalysis?.market?.tam || 1_000_000_000;
  const share = 0.0001; // 0.01% 市场渗透
  return Math.round(tam * share / 12);
}

function _estimateARR(type, ideaAnalysis) {
  const tam = ideaAnalysis?.market?.tam || 1_000_000_000;
  const share = 0.0001;
  return Math.round(tam * share);
}

function _modelFitScore(type, category, ideaAnalysis) {
  let score = 50;
  for (const rule of MODEL_FIT_RULES) {
    if (rule.prefer === type) {
      const pattern = rule.category || rule.pattern;
      if (pattern.test(category || "") || pattern.test(ideaAnalysis?.raw || "")) {
        score = rule.score;
        break;
      }
    }
  }
  return score;
}

function _modelPros(type) {
  switch (type) {
    case "saas": return ["可预测的经常性收入", "边际成本低", "易于扩展"];
    case "license": return ["高客单价", "现金流好", "客户锁定强"];
    case "subscription": return ["稳定的现金流", "客户粘性", "可预测"];
    case "freemium": return ["低获客成本", "病毒传播", "数据积累"];
    case "marketplace": return ["网络效应", "轻资产", "规模化"];
    case "enterprise": return ["超高客单价", "深度关系", "长期合作"];
    case "hybrid": return ["灵活", "覆盖多场景", "收入多元化"];
    default: return [];
  }
}

function _modelCons(type) {
  switch (type) {
    case "saas": return ["前期投入大", "竞争激烈", "需要持续迭代"];
    case "license": return ["销售周期长", "现金流波动", "增长天花板"];
    case "subscription": return ["流失风险", "需要持续价值交付", "定价敏感"];
    case "freemium": return ["转化率低", "免费用户成本", "收入不确定"];
    case "marketplace": return ["冷启动困难", "双边难题", "监管风险"];
    case "enterprise": return ["定制成本高", "规模化难", "依赖大客户"];
    case "hybrid": return ["模式复杂", "管理成本高", "品牌定位模糊"];
    default: return [];
  }
}

function _estimateCashflow(recommendation) {
  const months = [-24, -18, -12, -6, 0, 6, 12, 18, 24, 30, 36];
  return months.map(m => ({
    month: m,
    revenue: m <= 0 ? 0 : Math.round(recommendation.estimatedMRR * m * (1 + m * 0.05)),
    cost: Math.round(recommendation.estimatedMRR * 5 * (m <= 0 ? 1 : 1 + m * 0.02)),
    profit: 0,
  })).map(p => ({ ...p, profit: p.revenue - p.cost }));
}

function _generateReport(model, revenue, recommendation, alternatives, cashflow) {
  const lines = [
    `# Business Model Analysis Report`,
    "",
    "## Recommended Model",
    `**${MODEL_DESCRIPTIONS[model.type]?.label || model.type}** (Fit Score: ${recommendation.score}/100)`,
    "",
    "## Revenue Streams",
    ...recommendation.revenueStreams.map(s => `- ${s.name}: ${s.percentage}%`),
    "",
    "## Key Metrics",
    `- **ARPU:** $${recommendation.estimatedARPU.toLocaleString()}/year`,
    `- **LTV:** $${model.customerLTV.toLocaleString()}`,
    `- **CAC:** $${model.customerCAC.toLocaleString()}`,
    `- **LTV/CAC Ratio:** ${model.ltvCacRatio}x`,
    `- **Gross Margin:** ${model.grossMargin}%`,
    `- **Payback Period:** ${model.paybackMonths} months`,
    `- **Breakeven:** ${model.breakevenMonths} months`,
    "",
    "## Revenue Projections",
    `- **Year 1:** $${revenue.year1Revenue.toLocaleString()}`,
    `- **Year 3:** $${revenue.year3Revenue.toLocaleString()}`,
    `- **Year 5:** $${revenue.year5Revenue.toLocaleString()}`,
    "",
    "## Alternatives Considered",
    ...alternatives.map(a =>
      `### ${a.label} (${a.fitScore}/100)\n**Pros:** ${a.pros.join(", ")}\n**Cons:** ${a.cons.join(", ")}`),
    "",
    `---\n*Generated at ${new Date().toISOString()}*`,
  ];
  return lines.join("\n");
}
