/**
 * SF-01 Product Strategy Factory — Idea Analysis Engine
 *
 * Part B：产品创意分析引擎。
 *
 * 输入：自然语言产品想法
 * 输出：结构化产品战略分析
 *
 * 分析 10 个维度：
 *   1. 用户痛点    2. 用户需求    3. 市场规模    4. 行业阶段    5. 市场成熟度
 *   6. 替代方案    7. 付费意愿    8. 产品壁垒    9. 技术门槛    10. 竞争门槛
 *
 * 评分引擎：基于关键词 + 分类 + 行业知识库进行规则评分。
 * 纯函数，无副作用。
 *
 * @module sf-01-product-strategy/idea-analysis
 * @since SF-01
 */

import {
  createProductIdea, createProblemStatement,
  createTargetCustomer, createTargetMarket,
  createValueProposition, createCompetitiveLandscape,
} from "./domain-model.mjs";

// ═══════════════════════════════════════════════════════
// 行业知识库：类别 → 市场特征
// ═══════════════════════════════════════════════════════

const INDUSTRY_KNOWLEDGE = {
  erp: {
    category: "企业管理软件",
    maturity: "mature",
    growthRate: 8,
    competitionIntensity: 70,
    barrierToEntry: 65,
    willingnessToPay: 85,
    typicalTAM: 50_000_000_000,   // $50B
    typicalSAM: 20_000_000_000,
  },
  crm: {
    category: "企业管理软件",
    maturity: "mature",
    growthRate: 12,
    competitionIntensity: 80,
    barrierToEntry: 60,
    willingnessToPay: 80,
    typicalTAM: 80_000_000_000,
    typicalSAM: 30_000_000_000,
  },
  "ai-agent": {
    category: "AI 平台",
    maturity: "emerging",
    growthRate: 50,
    competitionIntensity: 60,
    barrierToEntry: 45,
    willingnessToPay: 70,
    typicalTAM: 30_000_000_000,
    typicalSAM: 5_000_000_000,
  },
  "ai-chatbot": {
    category: "AI 应用",
    maturity: "growing",
    growthRate: 35,
    competitionIntensity: 65,
    barrierToEntry: 30,
    willingnessToPay: 65,
    typicalTAM: 10_000_000_000,
    typicalSAM: 3_000_000_000,
  },
  "cross-border-ecommerce": {
    category: "跨境电商",
    maturity: "growing",
    growthRate: 20,
    competitionIntensity: 75,
    barrierToEntry: 50,
    willingnessToPay: 60,
    typicalTAM: 5_000_000_000_000,
    typicalSAM: 500_000_000_000,
  },
  cad: {
    category: "工业设计软件",
    maturity: "mature",
    growthRate: 6,
    competitionIntensity: 85,
    barrierToEntry: 90,
    willingnessToPay: 90,
    typicalTAM: 15_000_000_000,
    typicalSAM: 5_000_000_000,
  },
  mes: {
    category: "工业软件",
    maturity: "growing",
    growthRate: 15,
    competitionIntensity: 55,
    barrierToEntry: 75,
    willingnessToPay: 85,
    typicalTAM: 20_000_000_000,
    typicalSAM: 8_000_000_000,
  },
  "video-editing": {
    category: "创意工具",
    maturity: "growing",
    growthRate: 18,
    competitionIntensity: 70,
    barrierToEntry: 60,
    willingnessToPay: 55,
    typicalTAM: 3_000_000_000,
    typicalSAM: 1_000_000_000,
  },
  "customer-service": {
    category: "企业服务",
    maturity: "growing",
    growthRate: 25,
    competitionIntensity: 65,
    barrierToEntry: 40,
    willingnessToPay: 75,
    typicalTAM: 25_000_000_000,
    typicalSAM: 10_000_000_000,
  },
};

const DEFAULT_KNOWLEDGE = {
  category: "通用软件",
  maturity: "emerging",
  growthRate: 15,
  competitionIntensity: 50,
  barrierToEntry: 50,
  willingnessToPay: 50,
  typicalTAM: 1_000_000_000,
  typicalSAM: 100_000_000,
};

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

/**
 * 分析产品创意。
 *
 * 输入一句话产品想法，输出完整的 10 维度分析结果。
 *
 * @param {string} rawIdea — 自然语言产品想法
 * @returns {object} IdeaAnalysisResult
 *   { idea, problem, customer, market, valueProp, competitiveLandscape, scores, keywords, category, raw }
 */
export function analyzeProductIdea(rawIdea) {
  if (!rawIdea || typeof rawIdea !== "string" || rawIdea.trim().length === 0) {
    throw new TypeError("Product idea must be a non-empty string");
  }

  const raw = rawIdea.trim();

  // 1. 关键词提取
  const keywords = _extractKeywords(raw);
  const category = _classifyProduct(raw, keywords);

  // 2. 获取行业知识
  const knowledge = INDUSTRY_KNOWLEDGE[category] || { ...DEFAULT_KNOWLEDGE, category };
  const matchedKey = Object.keys(INDUSTRY_KNOWLEDGE).find(k => category.includes(k));
  const industryData = matchedKey ? INDUSTRY_KNOWLEDGE[matchedKey] : knowledge;

  // 3. 创建产品创意
  const idea = createProductIdea({
    raw,
    keywords,
    category: industryData.category || knowledge.category,
    subCategory: category,
  });

  // 4. 10 维度分析
  const painPointScore = _scorePainPoints(raw, industryData);
  const needScore = _scoreUserNeeds(raw, industryData);
  const marketSizeScore = _scoreMarketSize(industryData);
  const stageScore = _scoreIndustryStage(industryData);
  const maturityScore = _scoreMarketMaturity(industryData);
  const alternativeScore = _scoreAlternatives(raw, industryData);
  const willingnessScore = _scoreWillingness(industryData);
  const barrierScore = _scoreBarrier(industryData);
  const techBarrierScore = _scoreTechBarrier(raw, industryData);
  const competitionBarrierScore = _scoreCompetitionBarrier(industryData);

  // 5. 构建分析对象
  const problem = createProblemStatement({
    who: _targetUser(raw, industryData),
    what: raw,
    why: _whyImportant(raw, industryData),
    severity: painPointScore,
    frequency: Math.round((painPointScore + needScore) / 2),
  });

  const customer = createTargetCustomer({
    segment: _customerSegment(raw, industryData),
    painPoints: _derivePainPoints(raw, industryData),
    needs: _deriveNeeds(raw, industryData),
    willingnessToPay: willingnessScore,
    marketSize: _estimateCustomerCount(industryData),
    alternatives: _deriveAlternatives(raw, industryData),
  });

  const market = createTargetMarket({
    name: `${industryData.category || "未知"} 市场`,
    tam: Math.round(industryData.typicalTAM || knowledge.typicalTAM),
    sam: Math.round(industryData.typicalSAM || knowledge.typicalSAM),
    som: Math.round((industryData.typicalSAM || knowledge.typicalSAM) * 0.1),
    growthRate: industryData.growthRate || knowledge.growthRate,
    concentration: _marketConcentration(industryData.competitionIntensity),
    maturity: industryData.maturity || knowledge.maturity,
    aiImpact: _estimateAIImpact(raw, industryData),
  });

  const valueProp = createValueProposition({
    statement: _deriveValueStatement(raw, industryData),
    benefits: _deriveBenefits(raw, industryData),
    differentiators: _deriveDifferentiators(raw, industryData),
    valueScore: Math.round((needScore + willingnessScore) / 2),
    uniqueness: 100 - (industryData.competitionIntensity || 50),
  });

  const competitiveLandscape = createCompetitiveLandscape({
    directCompetitors: [],
    indirectCompetitors: [],
    competitionIntensity: industryData.competitionIntensity || 50,
    barrierToEntry: Math.max(barrierScore, techBarrierScore),
    moatStrength: competitionBarrierScore,
  });

  return {
    idea,
    problem,
    customer,
    market,
    valueProp,
    competitiveLandscape,
    scores: {
      painPoint: painPointScore,
      userNeed: needScore,
      marketSize: marketSizeScore,
      industryStage: stageScore,
      marketMaturity: maturityScore,
      alternativeRisk: alternativeScore,
      willingnessToPay: willingnessScore,
      productBarrier: barrierScore,
      techBarrier: techBarrierScore,
      competitionBarrier: competitionBarrierScore,
      overall: Math.round(
        (painPointScore + needScore + marketSizeScore + stageScore +
         maturityScore + (100 - alternativeScore) + willingnessScore +
         barrierScore + techBarrierScore + competitionBarrierScore) / 10
      ),
    },
    keywords,
    category: industryData.category || knowledge.category,
    raw,
  };
}

// ═══════════════════════════════════════════════════════
// 评分算法
// ═══════════════════════════════════════════════════════

/**
 * 1. 用户痛点评分 (0-100)
 * 基于痛点词密度 + 行业严重度
 */
function _scorePainPoints(raw, industry) {
  const painWords = ["痛", "难", "麻烦", "低效", "复杂", "昂贵", "慢", "差", "不", "无法", "缺乏", "落后", "人工", "手动"];
  let score = 40;
  for (const w of painWords) {
    if (raw.includes(w)) score += 5;
  }
  score += (industry.competitionIntensity || 50) * 0.1;
  return Math.min(100, Math.max(10, Math.round(score)));
}

/**
 * 2. 用户需求评分 (0-100)
 */
function _scoreUserNeeds(raw, industry) {
  const needWords = ["需要", "想要", "希望", "需求", "必须", "刚需", "高频", "日常", "核心"];
  let score = 40;
  for (const w of needWords) {
    if (raw.includes(w)) score += 6;
  }
  score += (industry.willingnessToPay || 50) * 0.2;
  return Math.min(100, Math.max(10, Math.round(score)));
}

/**
 * 3. 市场规模评分 (0-100)
 */
function _scoreMarketSize(industry) {
  const tam = industry.typicalTAM || 1_000_000_000;
  if (tam >= 100_000_000_000) return 95;
  if (tam >= 50_000_000_000) return 85;
  if (tam >= 10_000_000_000) return 70;
  if (tam >= 5_000_000_000) return 60;
  if (tam >= 1_000_000_000) return 45;
  return 30;
}

/**
 * 4. 行业阶段评分 (0-100)
 * emerging > growing > mature > declining
 */
function _scoreIndustryStage(industry) {
  switch (industry.maturity) {
    case "emerging":  return 85;
    case "growing":   return 75;
    case "mature":    return 50;
    case "declining": return 20;
    default:          return 50;
  }
}

/**
 * 5. 市场成熟度评分 (0-100)
 */
function _scoreMarketMaturity(industry) {
  return _scoreIndustryStage(industry);
}

/**
 * 6. 替代方案风险评分 (0-100, 越高越危险)
 */
function _scoreAlternatives(raw, industry) {
  let score = industry.competitionIntensity || 50;
  const altWords = ["替代", "已有", "竞品", "现有", "类似"];
  for (const w of altWords) {
    if (raw.includes(w)) score += 10;
  }
  return Math.min(100, Math.round(score));
}

/**
 * 7. 付费意愿评分 (0-100)
 */
function _scoreWillingness(industry) {
  return industry.willingnessToPay || 50;
}

/**
 * 8. 产品壁垒评分 (0-100)
 */
function _scoreBarrier(industry) {
  return industry.barrierToEntry || 50;
}

/**
 * 9. 技术门槛评分 (0-100)
 */
function _scoreTechBarrier(raw, industry) {
  let score = industry.barrierToEntry || 50;
  const techWords = ["AI", "ML", "深度学习", "CV", "NLP", "LLM", "大模型", "GPU", "3D", "渲染", "仿真", "实时"];
  for (const w of techWords) {
    if (raw.includes(w)) score += 10;
  }
  return Math.min(100, Math.round(score));
}

/**
 * 10. 竞争门槛评分 (0-100, 越高越难进入)
 */
function _scoreCompetitionBarrier(industry) {
  return industry.competitionIntensity || 50;
}

// ═══════════════════════════════════════════════════════
// 辅助函数
// ═══════════════════════════════════════════════════════

function _extractKeywords(raw) {
  const stopWords = new Set(["开发", "一个", "的", "了", "是", "在", "和", "与", "或"]);
  const words = raw.replace(/[，。！？、；：""（）《》\s]+/g, " ").split(" ");
  return words.filter(w => w.length >= 2 && !stopWords.has(w));
}

function _classifyProduct(raw, keywords) {
  const rules = [
    { pattern: /ERP|erp|企业资源/, cat: "erp" },
    { pattern: /CRM|crm|客户关系/, cat: "crm" },
    { pattern: /AI\s*Agent|AI智能体|Agent平台|AI\s*agent/, cat: "ai-agent" },
    { pattern: /AI客服|智能客服|AI\s*聊天|聊天机器人|chatbot|AI客服平台/, cat: "ai-chatbot" },
    { pattern: /跨境电商|cross.?border|跨境/, cat: "cross-border-ecommerce" },
    { pattern: /CAD|cad|计算机辅助设计/, cat: "cad" },
    { pattern: /MES|mes|制造执行|生产执行/, cat: "mes" },
    { pattern: /视频剪辑|视频编辑|video.?edit|剪辑软件/, cat: "video-editing" },
    { pattern: /客服|客户服务|customer.?service/, cat: "customer-service" },
    { pattern: /AI|人工智能|智能|大模型|LLM|深度学习/, cat: "ai-agent" },
    { pattern: /电商|ecommerce|电子商务/, cat: "cross-border-ecommerce" },
    { pattern: /SaaS|saas|企业级/, cat: "crm" },
  ];

  for (const r of rules) {
    if (r.pattern.test(raw)) return r.cat;
  }
  return "unknown";
}

function _targetUser(raw, industry) {
  if (/ERP|erp|企业|MES|mes/.test(raw)) return "企业决策者/IT负责人";
  if (/AI|客服|服务/.test(raw)) return "客服团队/运营团队";
  if (/电商|跨境/.test(raw)) return "跨境电商卖家企业";
  if (/CAD|cad|设计/.test(raw)) return "设计师/工程师";
  if (/视频|剪辑/.test(raw)) return "内容创作者/视频制作人";
  return "目标用户群体";
}

function _whyImportant(raw, industry) {
  return `当前${_targetUser(raw, industry)}面临${raw}方面的效率/成本/质量问题，市场缺乏满意的解决方案`;
}

function _customerSegment(raw, industry) {
  return _targetUser(raw, industry);
}

function _derivePainPoints(raw, industry) {
  const base = ["效率低下", "成本高昂", "质量不稳定"];
  if (/AI|智能/.test(raw)) base.push("自动化程度不足", "人工处理错误率高");
  if (/电商|跨境/.test(raw)) base.push("语言障碍", "物流复杂", "汇率波动");
  if (/ERP|erp|企业|MES/.test(raw)) base.push("系统集成困难", "数据孤岛", "定制成本高");
  return [...new Set(base)];
}

function _deriveNeeds(raw, industry) {
  const base = ["降低运营成本", "提升工作效率", "减少人工错误"];
  if (/AI|智能/.test(raw)) base.push("智能决策辅助", "24/7 自动化服务");
  if (/电商|跨境/.test(raw)) base.push("多语言支持", "供应链优化");
  if (/ERP|erp|企业|MES/.test(raw)) base.push("流程标准化", "实时数据看板");
  return [...new Set(base)];
}

function _deriveAlternatives(raw, industry) {
  const base = ["人工处理", "Excel/手动管理"];
  if (/AI|客服/.test(raw)) base.push("传统客服软件", "外包客服团队");
  if (/ERP|erp/.test(raw)) base.push("SAP", "Oracle", "用友");
  if (/电商|跨境/.test(raw)) base.push("Shopify", "独立站方案");
  if (/CAD|cad/.test(raw)) base.push("AutoCAD", "SolidWorks");
  return [...new Set(base)];
}

function _estimateCustomerCount(industry) {
  const tam = industry.typicalTAM || 1_000_000_000;
  const arpu = industry.willingnessToPay ? industry.willingnessToPay * 100 : 5000;
  return Math.max(100, Math.round(tam / arpu));
}

function _marketConcentration(intensity) {
  if (intensity >= 80) return "oligopoly";
  if (intensity >= 60) return "concentrated";
  if (intensity >= 40) return "moderate";
  return "fragmented";
}

function _estimateAIImpact(raw, industry) {
  if (/AI|人工智能|大模型|LLM|智能|Agent/.test(raw)) return 90;
  if (industry.category?.includes("AI")) return 85;
  if (industry.maturity === "emerging") return 60;
  return 30;
}

function _deriveValueStatement(raw, industry) {
  return `为${_targetUser(raw, industry)}提供${raw}解决方案，帮助他们降低 X% 成本/提升 Y% 效率`;
}

function _deriveBenefits(raw, industry) {
  const base = ["降低成本", "提升效率"];
  if (/AI|智能/.test(raw)) base.push("智能自动化", "数据驱动决策");
  if (/电商|跨境/.test(raw)) base.push("全球化覆盖", "多平台管理");
  if (/ERP|erp|企业|MES/.test(raw)) base.push("流程标准化", "实时监控");
  return [...new Set(base)];
}

function _deriveDifferentiators(raw, industry) {
  const base = ["更好的用户体验"];
  if (/AI|智能/.test(raw)) base.push("AI 驱动的智能化能力");
  if (industry.competitionIntensity < 60) base.push("蓝海市场先发优势");
  if (industry.barrierToEntry > 60) base.push("高技术壁垒");
  return [...new Set(base)];
}
