/**
 * SF-01 Product Strategy Factory — Market Analysis Engine
 *
 * Part C：市场分析引擎。
 *
 * 分析维度：
 *   TAM / SAM / SOM
 *   市场增长率
 *   市场竞争程度
 *   市场集中度
 *   行业趋势
 *   技术趋势
 *   AI 影响程度
 *   全球化机会
 *
 * @module sf-01-product-strategy/market-analysis
 * @since SF-01
 */

import { createTargetMarket } from "./domain-model.mjs";

// ═══════════════════════════════════════════════════════
// 市场数据知识库 (2026 基准)
// ═══════════════════════════════════════════════════════

const MARKET_TRENDS = {
  "企业管理软件": {
    trends: ["云化迁移加速", "AI 嵌入业务流", "低代码/无代码", "移动优先"],
    techTrends: ["LLM 集成", "RPA", "数据分析 AI"],
    globalization: 60,
  },
  "AI 平台": {
    trends: ["Agent 化", "多模态融合", "边缘 AI", "AI 安全合规"],
    techTrends: ["GPT-5+", "Agent 框架标准化", "RAG 进化", "Tool Use"],
    globalization: 80,
  },
  "AI 应用": {
    trends: ["垂直行业 AI", "AI 成本下降", "Agent 协作", "个性化 AI"],
    techTrends: ["多 Agent 系统", "Function Calling", "长上下文", "实时推理"],
    globalization: 75,
  },
  "跨境电商": {
    trends: ["社交电商崛起", "TikTok Shop", "独立站品牌化", "AI 选品"],
    techTrends: ["AI 翻译", "智能定价", "供应链 AI", "数字人直播"],
    globalization: 90,
  },
  "工业设计软件": {
    trends: ["云端 CAD", "AI 辅助设计", "协同设计", "数字孪生"],
    techTrends: ["生成式设计", "实时渲染", "WebGPU", "AI 仿真"],
    globalization: 65,
  },
  "工业软件": {
    trends: ["国产替代", "工业互联网", "数字孪生", "柔性制造"],
    techTrends: ["IoT 集成", "边缘计算", "AI 质检", "5G+工业"],
    globalization: 40,
  },
  "创意工具": {
    trends: ["AI 视频生成", "协作编辑", "模板化", "社交分享"],
    techTrends: ["Sora/Veo", "实时 AI 渲染", "云端处理", "多端同步"],
    globalization: 70,
  },
  "企业服务": {
    trends: ["SaaS 化", "AI Native", "PLG 增长", "垂直 SaaS"],
    techTrends: ["AI Copilot", "Workflow 自动化", "数据分析", "集成生态"],
    globalization: 55,
  },
};

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

/**
 * 执行市场分析。
 *
 * @param {object} ideaAnalysis — IdeaAnalysisResult (from idea-analysis)
 * @returns {object} MarketAnalysisResult
 *   { market, tamBreakdown, trends, risks, opportunities, report }
 */
export function analyzeMarket(ideaAnalysis) {
  if (!ideaAnalysis?.market) {
    throw new TypeError("Market analysis requires idea analysis result with market data");
  }

  const m = ideaAnalysis.market;
  const category = ideaAnalysis.category || "通用软件";
  const trendData = MARKET_TRENDS[category] || {
    trends: ["数字化转型", "云化"],
    techTrends: ["AI", "自动化"],
    globalization: 40,
  };

  // TAM 细分
  const tamBreakdown = _breakdownTAM(m, category);

  // 机会评估
  const opportunities = _assessOpportunities(m, trendData, category);

  // 风险评估
  const risks = _assessMarketRisks(m, category);

  // 全球化评分
  const globalizationScore = trendData.globalization || 40;

  // 综合报告
  const report = _generateReport(m, tamBreakdown, trendData, opportunities, risks, globalizationScore);

  return {
    market: m,
    tamBreakdown,
    trends: trendData.trends || [],
    techTrends: trendData.techTrends || [],
    opportunities,
    risks,
    globalizationScore,
    attractivenessScore: _marketAttractiveness(m, globalizationScore),
    report,
  };
}

// ═══════════════════════════════════════════════════════
// 内部分析
// ═══════════════════════════════════════════════════════

function _breakdownTAM(market, category) {
  const regions = {
    "中国": 0.30,
    "北美": 0.25,
    "欧洲": 0.20,
    "亚太(不含中国)": 0.15,
    "其他": 0.10,
  };

  const segments = {};
  for (const [region, pct] of Object.entries(regions)) {
    segments[region] = {
      tam: Math.round(market.tam * pct),
      percentage: Math.round(pct * 100),
      opportunity: pct > 0.2 ? "high" : pct > 0.1 ? "medium" : "low",
    };
  }

  return {
    byRegion: segments,
    somPercentage: market.tam > 0 ? Number((market.som / market.tam * 100).toFixed(2)) : 0,
    addressablePercentage: market.tam > 0 ? Number((market.sam / market.tam * 100).toFixed(2)) : 0,
  };
}

function _assessOpportunities(market, trendData, category) {
  const opps = [];

  if (market.growthRate > 20) {
    opps.push({ area: "高增长市场红利", score: 85, description: `市场年增长率 ${market.growthRate}%，处于快速增长期` });
  } else if (market.growthRate > 10) {
    opps.push({ area: "稳健增长市场", score: 65, description: `市场年增长率 ${market.growthRate}%，持续扩大` });
  }

  if (market.aiImpact > 60) {
    opps.push({ area: "AI 技术窗口", score: 80, description: "AI 正在重塑该行业，存在技术变革带来的机会窗口" });
  }

  if (trendData.globalization > 60) {
    opps.push({ area: "全球化扩展", score: 75, description: "产品具备全球化扩展潜力" });
  }

  if (market.concentration === "fragmented") {
    opps.push({ area: "碎片化市场整合", score: 70, description: "市场集中度低，存在整合和品牌化机会" });
  }

  if (opps.length === 0) {
    opps.push({ area: "差异化竞争", score: 50, description: "通过差异化和细分市场切入" });
  }

  return opps;
}

function _assessMarketRisks(market, category) {
  const risks = [];

  if (market.competitionIntensity > 70) {
    risks.push({ area: "激烈竞争", level: "high", description: "市场参与者众多，价格战风险高" });
  }

  if (market.growthRate < 5) {
    risks.push({ area: "增长停滞", level: "high", description: "市场增长乏力，天花板明显" });
  }

  if (market.maturity === "declining") {
    risks.push({ area: "市场萎缩", level: "critical", description: "行业处于衰退期" });
  }

  if (market.aiImpact > 70 && !category.includes("AI")) {
    risks.push({ area: "AI 颠覆风险", level: "medium", description: "AI 可能快速颠覆现有商业模式" });
  }

  if (risks.length === 0) {
    risks.push({ area: "一般市场风险", level: "low", description: "未发现显著市场风险" });
  }

  return risks;
}

function _marketAttractiveness(market, globalizationScore) {
  const scores = [
    Math.min(100, (market.growthRate || 0) * 2),
    market.maturity === "emerging" ? 85 : market.maturity === "growing" ? 70 : market.maturity === "mature" ? 45 : 20,
    (market.concentration === "fragmented" ? 80 : market.concentration === "moderate" ? 55 : 30),
    globalizationScore,
    100 - (market.competitionIntensity || 50),
  ];
  return Math.round(scores.reduce((a, b) => a + b, 0) / scores.length);
}

function _generateReport(market, tamBreakdown, trendData, opportunities, risks, globalizationScore) {
  const formatB = (v) => v >= 1e9 ? `$${(v / 1e9).toFixed(1)}B` : `$${(v / 1e6).toFixed(0)}M`;

  const lines = [
    `# Market Analysis Report: ${market.name}`,
    "",
    "## Market Size",
    `- **TAM:** ${formatB(market.tam)} (Total Addressable Market)`,
    `- **SAM:** ${formatB(market.sam)} (Serviceable Available Market)`,
    `- **SOM:** ${formatB(market.som)} (Serviceable Obtainable Market, ~${tamBreakdown.somPercentage}% of TAM)`,
    `- **Growth Rate:** ${market.growthRate}% CAGR`,
    "",
    "## TAM Breakdown by Region",
    ...Object.entries(tamBreakdown.byRegion).map(([r, d]) =>
      `- **${r}:** ${formatB(d.tam)} (${d.percentage}%) — ${d.opportunity}`),
    "",
    "## Market Characteristics",
    `- **Maturity:** ${market.maturity}`,
    `- **Concentration:** ${market.concentration}`,
    `- **Competition Intensity:** ${market.competitionIntensity}/100`,
    `- **AI Impact:** ${market.aiImpact}/100`,
    `- **Globalization Potential:** ${globalizationScore}/100`,
    "",
    "## Market Trends",
    ...(trendData.trends || []).map(t => `- ${t}`),
    "",
    "## Technology Trends",
    ...(trendData.techTrends || []).map(t => `- ${t}`),
    "",
    "## Opportunities",
    ...opportunities.map(o => `- **${o.area}** (${o.score}/100): ${o.description}`),
    "",
    "## Risks",
    ...risks.map(r => `- [${r.level}] **${r.area}**: ${r.description}`),
    "",
    `---\n*Generated at ${new Date().toISOString()}*`,
  ];

  return lines.join("\n");
}
