/**
 * SF-01 Product Strategy Factory — GTM & Roadmap Engines
 *
 * Part I：Go-To-Market Engine — 市场进入策略
 * Part J：Roadmap Generator — 产品路线图生成
 *
 * @module sf-01-product-strategy/gtm-roadmap
 * @since SF-01
 */

import {
  createGoToMarketStrategy, createRoadmap, createRoadmapPhase, ROADMAP_PHASE,
} from "./domain-model.mjs";

// ═══════════════════════════════════════════════════════
// Part I：Go-To-Market Engine
// ═══════════════════════════════════════════════════════

/**
 * 生成市场进入策略。
 *
 * @param {object} ideaAnalysis
 * @param {object} marketAnalysis
 * @param {object} competitorAnalysis
 * @param {object} businessModelResult
 * @returns {object} GTMResult
 */
export function generateGTM(ideaAnalysis, marketAnalysis, competitorAnalysis, businessModelResult) {
  const category = ideaAnalysis?.category || "unknown";
  const modelType = businessModelResult?.model?.type || "saas";

  // 进入策略
  const entryStrategy = _entryStrategy(category, marketAnalysis);
  const channels = _channelsForCategory(category);
  const acquisitionChannels = _acquisitionChannels(category, modelType);
  const coldStartPlan = _coldStartPlan(category, ideaAnalysis);
  const brandStrategy = _brandStrategy(category, ideaAnalysis);
  const growthModel = _growthModel(category, modelType, ideaAnalysis);

  const gtm = createGoToMarketStrategy({
    entryStrategy,
    channels,
    acquisitionChannels,
    coldStartPlan,
    brandStrategy,
    growthModel,
    timeToMarketMonths: _timeToMarket(category, ideaAnalysis),
    initialBudget: _initialBudget(category, ideaAnalysis),
  });

  const report = _generateGTMReport(gtm, ideaAnalysis, marketAnalysis);

  return {
    gtm,
    entryStrategy,
    coldStartPlan,
    channels,
    acquisitionChannels,
    brandStrategy,
    growthModel,
    report,
  };
}

function _entryStrategy(category, marketAnalysis) {
  const intensity = marketAnalysis?.market?.competitionIntensity || 50;
  if (intensity >= 80) return "利基市场切入 — 选择一个被巨头忽视的细分领域，深度满足特定用户需求";
  if (intensity >= 60) return "差异化切入 — 在核心功能上做到极致，通过差异化体验获客";
  if (intensity >= 40) return "品牌化切入 — 快速建立品牌认知，抢占用户心智";
  return "先发优势切入 — 快速占领市场，建立网络效应";
}

function _channelsForCategory(category) {
  if (/ERP|erp|MES|mes|企业|[企业级]/.test(category)) {
    return ["行业展会", "行业协会", "合作伙伴渠道", "内容营销(白皮书/案例)", "直销团队"];
  }
  if (/AI|智能|Agent/.test(category)) {
    return ["Product Hunt/GitHub", "技术社区", "内容营销(博客/视频)", "社交媒体(推特/X/知乎)", "API 市场"];
  }
  if (/电商|跨境/.test(category)) {
    return ["社交媒体(TikTok/小红书)", "KOL 合作", "电商平台内推广", "跨境社区/论坛", "SEO/SEM"];
  }
  if (/视频|剪辑/.test(category)) {
    return ["社交媒体(抖音/B站/YouTube)", "创作者社区", "模板市场", "KOL 测评", "应用商店优化"];
  }
  return ["内容营销", "社交传播", "SEO/SEM", "合作伙伴", "社区运营"];
}

function _acquisitionChannels(category, modelType) {
  if (modelType === "enterprise" || modelType === "license") {
    return ["出站销售(Outbound)", "行业会议/展会", "合作伙伴推荐", "内容营销(白皮书)"];
  }
  if (modelType === "freemium") {
    return ["免费版自然流量", "社交传播/病毒营销", "SEO/内容营销", "应用商店"];
  }
  if (modelType === "marketplace") {
    return ["SEO/SEM", "供应商 BD", "买家补贴", "社交传播"];
  }
  return ["内容营销/SEO", "社交传播", "付费广告", "合作伙伴/联盟营销"];
}

function _coldStartPlan(category, ideaAnalysis) {
  return `第 1 步：找到 10-50 个种子用户进行深度访谈 → 第 2 步：在 ${_coldStartPlatform(category)} 发布 MVP → 第 3 步：收集反馈快速迭代 → 第 4 步：通过用户口碑和内容营销扩大用户群 → 第 5 步：达到 1000 用户后启动付费转化`;
}

function _coldStartPlatform(category) {
  if (/AI|Agent/.test(category)) return "Product Hunt / GitHub / 即刻";
  if (/电商|跨境/.test(category)) return "小红书 / TikTok";
  if (/视频|剪辑/.test(category)) return "B站 / YouTube / 抖音";
  if (/企业|ERP/.test(category)) return "行业展会 / 行业协会";
  return "Product Hunt / 社交媒体";
}

function _brandStrategy(category, ideaAnalysis) {
  if (/AI|智能|Agent/.test(category)) return "技术领先品牌：通过技术博客、开源项目、行业会议建立技术影响力";
  if (/企业|ERP|MES/.test(category)) return "专业可靠品牌：通过案例研究、白皮书、行业认证建立信任";
  return "用户导向品牌：通过用户故事、社区运营、口碑传播建立品牌";
}

function _growthModel(category, modelType, ideaAnalysis) {
  if (modelType === "freemium") return "PLG (Product-Led Growth) — 免费版驱动获客，产品体验驱动转化";
  if (modelType === "marketplace") return "双边网络效应 — 供给端和需求端互相驱动增长";
  if (modelType === "enterprise" || modelType === "license") return "SLG (Sales-Led Growth) — 销售团队驱动大客户获取";
  return "PLG + SLG 混合 — 自助服务驱动中小客户，销售团队攻坚大客户";
}

function _timeToMarket(category, ideaAnalysis) {
  // 基于技术门槛估算上线时间
  const techBarrier = ideaAnalysis?.scores?.techBarrier || 50;
  if (techBarrier > 80) return 12;
  if (techBarrier > 60) return 8;
  if (techBarrier > 40) return 6;
  return 3;
}

function _initialBudget(category, ideaAnalysis) {
  const timeMonths = _timeToMarket(category, ideaAnalysis);
  // 简单估算法：3人团队 × $10k/月 × 月数
  return Math.round(3 * 10000 * timeMonths);
}

function _generateGTMReport(gtm, ideaAnalysis, marketAnalysis) {
  const lines = [
    `# Go-To-Market Strategy Report`,
    "",
    "## Entry Strategy",
    gtm.entryStrategy,
    "",
    "## Channels",
    ...gtm.channels.map(c => `- ${c}`),
    "",
    "## Acquisition Channels",
    ...gtm.acquisitionChannels.map(c => `- ${c}`),
    "",
    "## Cold Start Plan",
    gtm.coldStartPlan,
    "",
    "## Brand Strategy",
    gtm.brandStrategy,
    "",
    "## Growth Model",
    gtm.growthModel,
    "",
    "## Timeline & Budget",
    `- **Time to Market:** ${gtm.timeToMarketMonths} months`,
    `- **Initial Budget:** $${gtm.initialBudget.toLocaleString()}`,
    "",
    `---\n*Generated at ${new Date().toISOString()}*`,
  ];
  return lines.join("\n");
}

// ═══════════════════════════════════════════════════════
// Part J：Roadmap Generator
// ═══════════════════════════════════════════════════════

/**
 * 生成产品路线图。
 *
 * @param {object} ideaAnalysis
 * @param {object} viabilityResult
 * @returns {object} RoadmapResult
 */
export function generateRoadmap(ideaAnalysis, viabilityResult) {
  const category = ideaAnalysis?.category || "unknown";
  const raw = ideaAnalysis?.raw || "";

  const phases = [
    createRoadmapPhase({
      phase: ROADMAP_PHASE.MVP,
      goal: `验证核心价值：${raw} 的最小可行版本`,
      features: _mvpFeatures(category, raw),
      durationMonths: 3,
      teamSize: 3,
      budget: _phaseBudget(3, 3),
      successCriteria: [
        { metric: "种子用户数", target: "50-100" },
        { metric: "用户留存率(30天)", target: ">40%" },
        { metric: "核心功能使用率", target: ">60%" },
      ],
    }),
    createRoadmapPhase({
      phase: ROADMAP_PHASE.V1,
      goal: `产品市场匹配 (PMF)：打磨核心体验`,
      features: _v1Features(category, raw),
      durationMonths: 3,
      teamSize: 5,
      budget: _phaseBudget(3, 5),
      successCriteria: [
        { metric: "付费用户数", target: "500-1000" },
        { metric: "MRR", target: "$10K+" },
        { metric: "NPS", target: ">40" },
      ],
    }),
    createRoadmapPhase({
      phase: ROADMAP_PHASE.V2,
      goal: "规模化增长：扩展功能和用户群",
      features: _v2Features(category, raw),
      durationMonths: 6,
      teamSize: 8,
      budget: _phaseBudget(6, 8),
      successCriteria: [
        { metric: "付费用户数", target: "5000+" },
        { metric: "ARR", target: "$1M+" },
        { metric: "市场份额", target: "1-2%" },
      ],
    }),
    createRoadmapPhase({
      phase: ROADMAP_PHASE.V3,
      goal: "平台化与生态建设",
      features: _v3Features(category, raw),
      durationMonths: 9,
      teamSize: 15,
      budget: _phaseBudget(9, 15),
      successCriteria: [
        { metric: "API/插件生态", target: "100+ 集成" },
        { metric: "ARR", target: "$5M+" },
      ],
    }),
    createRoadmapPhase({
      phase: ROADMAP_PHASE.ENTERPRISE,
      goal: "企业版：大客户与私有化部署",
      features: ["SSO/SAML", "RBAC 权限", "审计日志", "SLA 99.9%", "私有化部署方案", "专属客户成功经理"],
      durationMonths: 6,
      teamSize: 10,
      budget: _phaseBudget(6, 10),
      successCriteria: [
        { metric: "企业客户数", target: "50+" },
        { metric: "企业 ARR", target: "$3M+" },
      ],
    }),
    createRoadmapPhase({
      phase: ROADMAP_PHASE.GLOBALIZATION,
      goal: "国际化：跨语言、跨区域扩展",
      features: ["多语言(i18n)", "多币种", "区域合规(GDPR/CCPA)", "全球 CDN", "本地化运营团队"],
      durationMonths: 9,
      teamSize: 12,
      budget: _phaseBudget(9, 12),
      successCriteria: [
        { metric: "海外用户占比", target: ">30%" },
        { metric: "支持语言", target: "8+" },
      ],
    }),
  ];

  const roadmap = createRoadmap({ phases });

  const report = _generateRoadmapReport(roadmap, ideaAnalysis);

  return { roadmap, phases, report };
}

function _mvpFeatures(category, raw) {
  const base = ["核心功能(最小集)", "用户注册/登录", "基础 UI"];
  if (/AI|智能/.test(raw)) base.push("AI 核心能力", "基础对话/交互");
  if (/ERP|erp/.test(raw)) base.push("基础数据录入", "简单报表");
  if (/电商|跨境/.test(raw)) base.push("商品管理", "基础交易");
  return base;
}

function _v1Features(category, raw) {
  return ["完善核心功能", "用户反馈系统", "数据分析看板", "支付集成", "性能优化"];
}

function _v2Features(category, raw) {
  return ["高级功能", "第三方集成/API", "团队协作", "移动端适配", "自动化工作流"];
}

function _v3Features(category, raw) {
  return ["开放平台/API", "插件/应用市场", "AI 高级功能", "大规模数据处理", "多租户架构"];
}

function _phaseBudget(months, teamSize) {
  return Math.round(months * teamSize * 10000);
}

function _generateRoadmapReport(roadmap, ideaAnalysis) {
  const lines = [
    `# Product Roadmap: ${ideaAnalysis?.raw || "New Product"}`,
    "",
    "## Timeline Overview",
    `- **Total Duration:** ${roadmap.totalDurationMonths} months`,
    `- **Total Budget:** $${roadmap.totalBudget.toLocaleString()}`,
    "",
    "## Phase Details",
    ...roadmap.phases.map(p => {
      const features = p.features.map(f => `  - ${f}`).join("\n");
      const criteria = (p.successCriteria || []).map(c => `  - ${c.metric}: ${c.target}`).join("\n");
      return `### ${p.phase.toUpperCase()} — ${p.goal}\n\n**Duration:** ${p.durationMonths} months\n**Team:** ${p.teamSize} people\n**Budget:** $${p.budget.toLocaleString()}\n\n**Features:**\n${features}\n\n**Success Criteria:**\n${criteria}\n`;
    }),
    "",
    `---\n*Generated at ${new Date().toISOString()}*`,
  ];
  return lines.join("\n");
}
