/**
 * SF-01 Product Strategy Factory — Competitor Analysis Engine
 *
 * Part D：竞品分析引擎。
 *
 * 分析维度：
 *   直接竞品 / 间接竞品 / 替代方案
 *   产品功能 / 商业模式 / 价格策略 / 获客策略
 *   市场占有率 / 技术优势 / 产品优势 / 用户口碑
 *
 * @module sf-01-product-strategy/competitor-analysis
 * @since SF-01
 */

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

// ═══════════════════════════════════════════════════════
// 竞品知识库
// ═══════════════════════════════════════════════════════

const COMPETITOR_KNOWLEDGE = {
  erp: {
    leaders: [
      { name: "SAP S/4HANA", type: "direct", marketShare: 22, featureScore: 90, priceTier: "enterprise", strength: "全球生态+全模块", weakness: "贵+重" },
      { name: "Oracle NetSuite", type: "direct", marketShare: 15, featureScore: 85, priceTier: "mid", strength: "云原生+灵活", weakness: "中国市场弱" },
      { name: "用友 U8+", type: "direct", marketShare: 18, featureScore: 80, priceTier: "mid", strength: "本地化+渠道", weakness: "技术老化" },
      { name: "金蝶云星空", type: "direct", marketShare: 12, featureScore: 78, priceTier: "mid", strength: "云+SaaS", weakness: "定制弱" },
      { name: "Excel + 手动", type: "substitute", marketShare: 15, featureScore: 10, priceTier: "free", strength: "免费+灵活", weakness: "不成体系" },
    ],
  },
  "ai-agent": {
    leaders: [
      { name: "OpenAI GPTs", type: "direct", marketShare: 35, featureScore: 95, priceTier: "freemium", strength: "生态+品牌+技术", weakness: "封闭生态" },
      { name: "LangChain/LangGraph", type: "indirect", marketShare: 25, featureScore: 85, priceTier: "free", strength: "开源+灵活", weakness: "需开发" },
      { name: "Coze/扣子", type: "direct", marketShare: 10, featureScore: 80, priceTier: "freemium", strength: "低门槛+中文", weakness: "平台锁定" },
      { name: "Dify", type: "direct", marketShare: 8, featureScore: 75, priceTier: "freemium", strength: "开源+可视化", weakness: "企业功能弱" },
    ],
  },
  "ai-chatbot": {
    leaders: [
      { name: "Intercom Fin", type: "direct", marketShare: 20, featureScore: 88, priceTier: "premium", strength: "全渠道+AI", weakness: "贵" },
      { name: "Zendesk AI", type: "direct", marketShare: 18, featureScore: 85, priceTier: "premium", strength: "生态+集成", weakness: "复杂" },
      { name: "智齿科技", type: "direct", marketShare: 12, featureScore: 75, priceTier: "mid", strength: "中文+全渠道", weakness: "AI能力弱" },
      { name: "人工客服团队", type: "substitute", marketShare: 25, featureScore: 60, priceTier: "premium", strength: "灵活性", weakness: "成本+效率" },
    ],
  },
  cad: {
    leaders: [
      { name: "AutoCAD", type: "direct", marketShare: 35, featureScore: 95, priceTier: "enterprise", strength: "行业标准", weakness: "贵+重" },
      { name: "SolidWorks", type: "direct", marketShare: 25, featureScore: 90, priceTier: "enterprise", strength: "3D+仿真", weakness: "Windows绑定" },
      { name: "Fusion 360", type: "direct", marketShare: 10, featureScore: 80, priceTier: "mid", strength: "云+协作", weakness: "功能浅" },
      { name: "Onshape", type: "direct", marketShare: 5, featureScore: 75, priceTier: "mid", strength: "纯云+浏览器", weakness: "生态小" },
    ],
  },
  "video-editing": {
    leaders: [
      { name: "Adobe Premiere Pro", type: "direct", marketShare: 35, featureScore: 95, priceTier: "subscription", strength: "行业标准+生态", weakness: "学习曲线" },
      { name: "DaVinci Resolve", type: "direct", marketShare: 20, featureScore: 90, priceTier: "freemium", strength: "免费+专业调色", weakness: "硬件要求" },
      { name: "剪映/CapCut", type: "direct", marketShare: 25, featureScore: 80, priceTier: "freemium", strength: "AI+模板+社交", weakness: "专业功能弱" },
      { name: "Final Cut Pro", type: "direct", marketShare: 10, featureScore: 88, priceTier: "one-time", strength: "性能+体验", weakness: "Mac独占" },
    ],
  },
};

/**
 * 执行竞品分析。
 *
 * @param {object} ideaAnalysis — IdeaAnalysisResult
 * @returns {object} CompetitorAnalysisResult
 */
export function analyzeCompetitors(ideaAnalysis) {
  // 优先使用 subCategory（分类 ID），回退到 category（行业名称）
  const lookupKey = ideaAnalysis?.idea?.subCategory || ideaAnalysis?.subCategory || ideaAnalysis?.category || "unknown";
  const knowledge = COMPETITOR_KNOWLEDGE[lookupKey] || COMPETITOR_KNOWLEDGE[ideaAnalysis?.category];

  if (!knowledge) {
    return _unknownCategoryResult(lookupKey, ideaAnalysis);
  }

  const direct = knowledge.leaders.filter(c => c.type === "direct");
  const indirect = knowledge.leaders.filter(c => c.type === "indirect");
  const substitutes = knowledge.leaders.filter(c => c.type === "substitute");

  // 竞争强度计算
  const totalShare = knowledge.leaders.reduce((s, c) => s + (c.marketShare || 0), 0);
  const top3Share = knowledge.leaders.slice(0, 3).reduce((s, c) => s + (c.marketShare || 0), 0);

  const competitiveLandscape = createCompetitiveLandscape({
    directCompetitors: direct.map(c => ({
      name: c.name, type: c.type, marketShare: c.marketShare, featureScore: c.featureScore,
      priceTier: c.priceTier, strength: c.strength, weakness: c.weakness,
    })),
    indirectCompetitors: indirect.map(c => ({
      name: c.name, type: c.type, marketShare: c.marketShare, featureScore: c.featureScore,
      priceTier: c.priceTier, strength: c.strength, weakness: c.weakness,
    })),
    substitutes: substitutes.map(c => c.name),
    competitionIntensity: _intensityFromShare(top3Share),
    barrierToEntry: _barrierFromLeaders(knowledge.leaders),
    moatStrength: _moatFromGap(knowledge.leaders),
  });

  const report = _generateReport(lookupKey, knowledge, competitiveLandscape, top3Share);

  return {
    category: lookupKey,
    directCompetitors: direct,
    indirectCompetitors: indirect,
    substitutes,
    competitiveLandscape,
    top3MarketShare: top3Share,
    herfindahlIndex: _herfindahl(knowledge.leaders),
    fragmentationIndex: 100 - top3Share,
    report,
  };
}

function _unknownCategoryResult(lookupKey, ideaAnalysis) {
  const cl = createCompetitiveLandscape({
    competitionIntensity: 50, barrierToEntry: 50, moatStrength: 50,
  });
  return {
    category: lookupKey,
    directCompetitors: [],
    indirectCompetitors: [],
    substitutes: [],
    competitiveLandscape: cl,
    top3MarketShare: 0,
    herfindahlIndex: 0,
    fragmentationIndex: 100,
    report: `# Competitor Analysis Report\n\n## ${ideaAnalysis?.category || "Unknown"} Market\n\n_No competitor data available for this category. Manual research required._\n`,
  };
}

function _intensityFromShare(top3) {
  if (top3 >= 80) return 90;
  if (top3 >= 60) return 75;
  if (top3 >= 40) return 55;
  return 35;
}

function _barrierFromLeaders(leaders) {
  const avgFeatureScore = leaders.reduce((s, c) => s + (c.featureScore || 50), 0) / leaders.length;
  if (avgFeatureScore >= 85) return 85;
  if (avgFeatureScore >= 70) return 65;
  return 45;
}

function _moatFromGap(leaders) {
  const scores = leaders.map(c => c.featureScore || 50);
  if (scores.length === 0) return 50;
  const maxScore = Math.max(...scores);
  return Math.min(95, maxScore + 10);
}

function _herfindahl(leaders) {
  return Math.round(leaders.reduce((s, c) => s + (c.marketShare || 0) ** 2, 0));
}

function _generateReport(category, knowledge, cl, top3Share) {
  const lines = [
    `# Competitor Analysis Report: ${category}`,
    "",
    "## Market Structure",
    `- **Top 3 Market Share:** ${top3Share}%`,
    `- **HHI (Herfindahl):** ${_herfindahl(knowledge.leaders)} (${_hhiLabel(_herfindahl(knowledge.leaders))})`,
    `- **Competition Intensity:** ${cl.competitionIntensity}/100`,
    `- **Barrier to Entry:** ${cl.barrierToEntry}/100`,
    "",
    "## Direct Competitors",
    ...(knowledge.leaders.filter(c => c.type === "direct").map(c =>
      `### ${c.name}\n- **Market Share:** ${c.marketShare}%\n- **Feature Score:** ${c.featureScore}/100\n- **Price Tier:** ${c.priceTier}\n- **Strength:** ${c.strength}\n- **Weakness:** ${c.weakness}\n`)),
    "## Indirect Competitors",
    ...(knowledge.leaders.filter(c => c.type === "indirect").length > 0
      ? knowledge.leaders.filter(c => c.type === "indirect").map(c => `- **${c.name}:** ${c.strength} (Share: ${c.marketShare}%)`)
      : ["_None identified_"]),
    "",
    "## Substitutes",
    ...(knowledge.leaders.filter(c => c.type === "substitute").map(c => `- **${c.name}:** ${c.strength}`)),
    "",
    "## Competitive Strategy Recommendation",
    ..._strategyRecommendation(cl, top3Share),
    "",
    `---\n*Generated at ${new Date().toISOString()}*`,
  ];
  return lines.join("\n");
}

function _hhiLabel(hhi) {
  if (hhi > 2500) return "Highly Concentrated";
  if (hhi > 1500) return "Moderately Concentrated";
  return "Unconcentrated";
}

function _strategyRecommendation(cl, top3Share) {
  if (cl.competitionIntensity >= 80) {
    return ["- 避开巨头主战场，寻找细分利基市场", "- 通过差异化功能而非价格竞争", "- 考虑平台生态策略"];
  }
  if (top3Share <= 40) {
    return ["- 碎片化市场，存在品牌化机会", "- 快速占领心智，建立行业标准", "- 通过产品体验和口碑获客"];
  }
  return ["- 中等竞争市场，找准定位切入", "- 聚焦 1-2 个核心差异点", "- 利用 AI/新技术建立护城河"];
}
