/**
 * SF-01 Product Strategy Factory — Viability & Prioritization Engines
 *
 * Part F：Product Viability Engine (0-100 评分)
 * Part G：Product Prioritization Engine (P0-P3 优先级)
 * Part H：Product Vision Generator (Vision/Mission/North Star)
 *
 * @module sf-01-product-strategy/viability
 * @since SF-01
 */

import {
  createProductVision, createRiskAssessment, createSuccessMetric,
} from "./domain-model.mjs";

// ═══════════════════════════════════════════════════════
// Part F：Product Viability Engine
// ═══════════════════════════════════════════════════════

/**
 * 评估产品可行性。
 *
 * 6 维度评分（各 0-100）：
 *   Market Score — 市场吸引力
 *   Technical Score — 技术可行性
 *   Competition Score — 竞争优势
 *   Monetization Score — 变现能力
 *   Execution Score — 执行可行性
 *   Risk Score — 风险反向评分
 *
 * @param {object} ideaAnalysis
 * @param {object} [marketAnalysis]
 * @param {object} [competitorAnalysis]
 * @param {object} [businessModelResult]
 * @returns {object} ViabilityResult
 */
export function evaluateViability(ideaAnalysis, marketAnalysis, competitorAnalysis, businessModelResult) {
  const scores = {
    market: _marketScore(marketAnalysis, ideaAnalysis),
    technical: _technicalScore(ideaAnalysis),
    competition: _competitionScore(competitorAnalysis, ideaAnalysis),
    monetization: _monetizationScore(businessModelResult, ideaAnalysis),
    execution: _executionScore(ideaAnalysis),
    risk: _riskScore(ideaAnalysis), // 风险反向分（0 风险 = 100 分）
  };

  const overall = Math.round(
    (scores.market * 0.25) +
    (scores.technical * 0.15) +
    (scores.competition * 0.20) +
    (scores.monetization * 0.20) +
    (scores.execution * 0.10) +
    (scores.risk * 0.10)
  );

  const verdict = _viabilityVerdict(overall);

  return {
    scores,
    overall,
    verdict,
    breakdown: {
      market: { score: scores.market, weight: 25, description: "市场吸引力" },
      technical: { score: scores.technical, weight: 15, description: "技术可行性" },
      competition: { score: scores.competition, weight: 20, description: "竞争优势" },
      monetization: { score: scores.monetization, weight: 20, description: "变现能力" },
      execution: { score: scores.execution, weight: 10, description: "执行可行性" },
      risk: { score: scores.risk, weight: 10, description: "风险可控性" },
    },
    recommendation: _viabilityRecommendation(overall, scores),
  };
}

function _marketScore(marketAnalysis, ideaAnalysis) {
  const m = marketAnalysis || {};
  return Math.round(
    (m.attractivenessScore || 50) * 0.5 +
    (ideaAnalysis?.scores?.marketSize || 50) * 0.3 +
    (ideaAnalysis?.scores?.industryStage || 50) * 0.2
  );
}

function _technicalScore(ideaAnalysis) {
  const scores = ideaAnalysis?.scores || {};
  return Math.round(
    (scores.techBarrier || 50) * 0.4 +
    (scores.productBarrier || 50) * 0.3 +
    (100 - (scores.alternativeRisk || 50)) * 0.3
  );
}

function _competitionScore(competitorAnalysis, ideaAnalysis) {
  const cl = competitorAnalysis?.competitiveLandscape;
  if (!cl) return 50;
  return Math.round(
    (100 - (cl.competitionIntensity || 50)) * 0.5 +
    (cl.moatStrength || 50) * 0.3 +
    (cl.barrierToEntry || 50) * 0.2
  );
}

function _monetizationScore(businessModelResult, ideaAnalysis) {
  if (!businessModelResult?.model) return 50;
  const m = businessModelResult.model;
  return Math.round(
    Math.min(100, m.grossMargin || 60) * 0.3 +
    Math.min(100, (m.ltvCacRatio || 1) * 20) * 0.3 +
    (ideaAnalysis?.scores?.willingnessToPay || 50) * 0.4
  );
}

function _executionScore(ideaAnalysis) {
  const scores = ideaAnalysis?.scores || {};
  const barrier = scores.techBarrier || 50;
  // 壁垒越高执行越难
  return 100 - barrier * 0.7;
}

function _riskScore(ideaAnalysis) {
  const scores = ideaAnalysis?.scores || {};
  return 100 - (scores.alternativeRisk || 50);
}

function _viabilityVerdict(overall) {
  if (overall >= 80) return "STRONG_GO";
  if (overall >= 65) return "GO";
  if (overall >= 50) return "CONDITIONAL_GO";
  if (overall >= 35) return "HIGH_RISK";
  return "NO_GO";
}

function _viabilityRecommendation(overall, scores) {
  if (overall >= 80) return "产品具备极强可行性和市场吸引力。全力推进。";
  if (overall >= 65) return "产品可行。建议在进入前完善 GTM 策略。";
  if (overall >= 50) return "产品有条件可行。需在 X 领域补强后推进。";
  if (overall >= 35) return "产品高风险。建议深入市场验证后再决定。";
  return "不建议推进。市场/竞争/变现至少一项存在致命短板。";
}

// ═══════════════════════════════════════════════════════
// Part G：Product Prioritization Engine
// ═══════════════════════════════════════════════════════

export const PRIORITY_LEVEL = Object.freeze({
  P0: "p0", // 立即执行
  P1: "p1", // 尽快执行
  P2: "p2", // 计划执行
  P3: "p3", // 未来考虑
});

/**
 * 评估产品优先级。
 *
 * 6 维度评分：
 *   Value Score — 用户价值
 *   Cost Score — 开发成本 (反向)
 *   Risk Score — 风险
 *   Strategic Score — 战略价值
 *   Growth Score — 增长价值
 *   Technical Score — 技术价值
 *
 * @param {object} ideaAnalysis
 * @param {object} viabilityResult
 * @returns {object} PriorityResult
 */
export function evaluatePriority(ideaAnalysis, viabilityResult) {
  const scores = {
    value: _valueScore(ideaAnalysis),
    cost: _costScore(ideaAnalysis),
    risk: _riskPriorityScore(ideaAnalysis),
    strategic: _strategicScore(ideaAnalysis),
    growth: _growthScore(ideaAnalysis),
    technical: _technicalPriorityScore(ideaAnalysis, viabilityResult),
  };

  const weighted = Math.round(
    scores.value * 0.30 +
    scores.cost * 0.15 +
    scores.risk * 0.10 +
    scores.strategic * 0.20 +
    scores.growth * 0.15 +
    scores.technical * 0.10
  );

  const level = _priorityLevel(weighted);

  return {
    scores,
    weighted,
    level,
    label: _priorityLabel(level),
    recommendation: _priorityRecommendation(level),
  };
}

function _valueScore(ideaAnalysis) {
  const s = ideaAnalysis?.scores || {};
  return Math.round((s.painPoint || 50) * 0.4 + (s.userNeed || 50) * 0.4 + (s.willingnessToPay || 50) * 0.2);
}

function _costScore(ideaAnalysis) {
  const s = ideaAnalysis?.scores || {};
  // 低壁垒 = 低成本 = 高分
  return 100 - Math.round(((s.techBarrier || 50) + (s.productBarrier || 50)) / 2);
}

function _riskPriorityScore(ideaAnalysis) {
  // 低风险 = 高分 = 高优先级
  return 100 - Math.round(
    ((ideaAnalysis?.scores?.alternativeRisk || 50) +
     (ideaAnalysis?.scores?.competitionBarrier || 50)) / 2
  );
}

function _strategicScore(ideaAnalysis) {
  const s = ideaAnalysis?.scores || {};
  return Math.round(
    (s.marketSize || 50) * 0.4 +
    (s.industryStage || 50) * 0.3 +
    (s.marketMaturity || 50) * 0.3
  );
}

function _growthScore(ideaAnalysis) {
  const market = ideaAnalysis?.market;
  if (!market) return 50;
  return Math.min(100, Math.round(market.growthRate * 2));
}

function _technicalPriorityScore(ideaAnalysis, viabilityResult) {
  return viabilityResult?.scores?.technical || 50;
}

function _priorityLevel(score) {
  if (score >= 75) return PRIORITY_LEVEL.P0;
  if (score >= 60) return PRIORITY_LEVEL.P1;
  if (score >= 45) return PRIORITY_LEVEL.P2;
  return PRIORITY_LEVEL.P3;
}

function _priorityLabel(level) {
  switch (level) {
    case PRIORITY_LEVEL.P0: return "P0 — 立即执行";
    case PRIORITY_LEVEL.P1: return "P1 — 尽快执行";
    case PRIORITY_LEVEL.P2: return "P2 — 计划执行";
    case PRIORITY_LEVEL.P3: return "P3 — 未来考虑";
    default: return "P3";
  }
}

function _priorityRecommendation(level) {
  switch (level) {
    case PRIORITY_LEVEL.P0: return "高优先级产品。建议立即分配资源，进入 SF-02 需求工程。";
    case PRIORITY_LEVEL.P1: return "中高优先级。建议在 P0 之后排期，1-2 周内启动。";
    case PRIORITY_LEVEL.P2: return "中等优先级。列入产品待办，季度规划时评估。";
    case PRIORITY_LEVEL.P3: return "低优先级。保持关注，暂不投入资源。";
    default: return "";
  }
}

// ═══════════════════════════════════════════════════════
// Part H：Product Vision Generator
// ═══════════════════════════════════════════════════════

/**
 * 自动生成产品愿景。
 *
 * @param {object} ideaAnalysis
 * @param {object} [marketAnalysis]
 * @returns {object} VisionResult
 */
export function generateVision(ideaAnalysis, marketAnalysis) {
  const raw = ideaAnalysis?.raw || "";
  const category = ideaAnalysis?.category || "通用软件";
  const targetUser = ideaAnalysis?.customer?.segment || "目标用户";

  const vision = `让每个${targetUser}都能轻松实现${raw}`;
  const mission = `通过技术创新，为${targetUser}提供最好的${raw}解决方案`;
  const northStar = _deriveNorthStar(category, raw);
  const coreValues = _deriveCoreValues(category, raw);
  const longTermGoal = `成为${category}领域的全球领导者，服务百万用户`;

  const productVision = createProductVision({
    vision, mission, northStarMetric: northStar,
    coreValues, longTermGoal,
  });

  const riskAssessment = createRiskAssessment({
    risks: _deriveVisionRisks(ideaAnalysis, marketAnalysis),
    overallRisk: ideaAnalysis?.scores?.alternativeRisk || 50,
    marketRisk: ideaAnalysis?.scores?.competitionBarrier || 50,
    techRisk: ideaAnalysis?.scores?.techBarrier || 50,
    executionRisk: ideaAnalysis?.scores?.productBarrier || 50,
    competitionRisk: ideaAnalysis?.competitiveLandscape?.competitionIntensity || 50,
    financialRisk: 100 - (ideaAnalysis?.scores?.willingnessToPay || 50),
  });

  const successMetric = createSuccessMetric({
    northStar,
    kpis: _deriveKPIs(category),
    milestones: _deriveMilestones(),
  });

  return {
    productVision,
    riskAssessment,
    successMetric,
    summary: { vision, mission, northStar, coreValues, longTermGoal },
  };
}

function _deriveNorthStar(category, raw) {
  if (/AI|Agent|智能/.test(raw)) return "活跃 Agent 数量 / 自动化任务完成量";
  if (/ERP|erp|MES|mes|企业/.test(raw)) return "月活跃企业用户数";
  if (/客服|服务/.test(raw)) return "日均处理会话数";
  if (/电商|跨境/.test(raw)) return "月 GMV 交易额";
  if (/视频|剪辑/.test(raw)) return "月活跃创作者数";
  if (/CAD|cad|设计/.test(raw)) return "月活跃设计师数";
  return "日活跃用户数 (DAU)";
}

function _deriveCoreValues(category, raw) {
  const base = ["用户至上", "数据驱动", "持续创新"];
  if (/AI|智能/.test(raw)) base.push("AI First", "自动化优先");
  if (/企业/.test(raw)) base.push("安全可靠", "企业级品质");
  return [...new Set(base)];
}

function _deriveVisionRisks(ideaAnalysis, marketAnalysis) {
  const risks = [];
  const urgency = ideaAnalysis?.scores?.alternativeRisk || 50;
  if (urgency > 60) risks.push({ name: "市场时机", level: "high", description: "替代方案丰富，窗口期紧迫", mitigation: "加速 MVP 开发，抢占先机", probability: urgency });
  if (ideaAnalysis?.market?.competitionIntensity > 70) risks.push({ name: "激烈竞争", level: "high", description: "市场集中度高", mitigation: "差异化定位", probability: 70 });
  if (ideaAnalysis?.scores?.techBarrier > 70) risks.push({ name: "技术风险", level: "medium", description: "技术实现难度大", mitigation: "分阶段交付，MVP 验证核心技术", probability: 65 });
  if (risks.length === 0) risks.push({ name: "一般风险", level: "low", description: "未发现显著风险", mitigation: "常规风险管控", probability: 30 });
  return risks;
}

function _deriveKPIs(category) {
  return [
    { name: "用户增长率", target: "20% MoM", unit: "%", timeframe: "6个月" },
    { name: "用户留存率", target: ">60%", unit: "%", timeframe: "3个月" },
    { name: "NPS", target: ">40", unit: "score", timeframe: "6个月" },
  ];
}

function _deriveMilestones() {
  return [
    { phase: "MVP", target: "100 名种子用户验证核心价值", deadline: "第 3 个月" },
    { phase: "V1.0", target: "1000 名付费用户", deadline: "第 6 个月" },
    { phase: "V2.0", target: "产品市场匹配 (PMF) 确认", deadline: "第 12 个月" },
  ];
}
