/**
 * SF-01 Product Strategy Factory — Factory Entry Point
 *
 * Part K：Product Strategy Package（统一输出）
 * Part L：Factory Integration（注册到 PR-36 Factory Registry）
 * Part M：Artifacts（7 种战略产物）
 *
 * 输入：一句话产品想法
 * 输出：完整 Product Strategy Package
 *
 * 流程：
 *   1. Idea Analysis       → 10 维度创意评分
 *   2. Market Analysis     → TAM/SAM/SOM + 趋势
 *   3. Competitor Analysis → 竞品全景
 *   4. Business Model      → 商业模式推荐 + 财务
 *   5. Viability Scoring   → 0-100 可行性评分
 *   6. Prioritization      → P0-P3 优先级
 *   7. Vision Generation   → 愿景/使命/北极星
 *   8. GTM Strategy        → 市场进入策略
 *   9. Roadmap Generation  → MVP→V3→Enterprise→Global
 *   10. Strategy Package   → 统一输出
 *
 * @module sf-01-product-strategy
 * @since SF-01
 */

import { analyzeProductIdea } from "./idea-analysis.mjs";
import { analyzeMarket } from "./market-analysis.mjs";
import { analyzeCompetitors } from "./competitor-analysis.mjs";
import { analyzeBusinessModel } from "./business-model.mjs";
import { evaluateViability, evaluatePriority, generateVision, PRIORITY_LEVEL } from "./viability.mjs";
import { generateGTM, generateRoadmap } from "./gtm-roadmap.mjs";
import { createFactoryArtifact, createFactoryMetric, createFactoryOutput } from "../software-factory-core/factory-contract.mjs";

// ═══════════════════════════════════════════════════════
// Factory Artifact Constants
// ═══════════════════════════════════════════════════════

export const SF01_ARTIFACTS = Object.freeze({
  STRATEGY_PACKAGE:   "product-strategy-package",
  MARKET_ANALYSIS:    "market-analysis-report",
  COMPETITOR_REPORT:  "competitor-report",
  BUSINESS_MODEL:     "business-model-report",
  GTM_REPORT:         "gtm-report",
  ROADMAP_REPORT:     "roadmap-report",
  VIABILITY_REPORT:   "viability-report",
});

// ═══════════════════════════════════════════════════════
// Part K：Product Strategy Package
// ═══════════════════════════════════════════════════════

/**
 * 生成 Product Strategy Package。
 *
 * @param {object} ideaAnalysis
 * @param {object} marketResult
 * @param {object} competitorResult
 * @param {object} businessModelResult
 * @param {object} viabilityResult
 * @param {object} priorityResult
 * @param {object} visionResult
 * @param {object} gtmResult
 * @param {object} roadmapResult
 * @returns {object} StrategyPackage
 */
export function createStrategyPackage({
  ideaAnalysis, marketResult, competitorResult,
  businessModelResult, viabilityResult, priorityResult,
  visionResult, gtmResult, roadmapResult,
}) {
  const raw = ideaAnalysis?.raw || "Unknown";

  return {
    // Executive Summary
    executiveSummary: {
      title: `Product Strategy: ${raw}`,
      viabilityVerdict: viabilityResult?.verdict || "UNKNOWN",
      viabilityScore: viabilityResult?.overall || 0,
      priorityLevel: priorityResult?.level || PRIORITY_LEVEL.P3,
      recommendation: priorityResult?.recommendation || "",
    },

    // Problem & Customer
    problemStatement: ideaAnalysis?.problem || null,
    targetCustomer: ideaAnalysis?.customer || null,
    targetMarket: ideaAnalysis?.market || null,

    // Analysis
    competitiveAnalysis: {
      landscape: competitorResult?.competitiveLandscape || null,
      directCompetitors: competitorResult?.directCompetitors || [],
      top3Share: competitorResult?.top3MarketShare || 0,
    },

    // Business
    businessModel: businessModelResult?.model || null,
    revenueModel: businessModelResult?.revenue || null,

    // Strategy
    productVision: visionResult?.productVision || null,
    northStarMetric: visionResult?.summary?.northStar || "",
    riskAssessment: visionResult?.riskAssessment || null,
    successMetrics: visionResult?.successMetric || null,

    // Execution
    gtmStrategy: gtmResult?.gtm || null,
    roadmap: roadmapResult?.roadmap || null,

    // Scores
    viability: viabilityResult?.scores || null,
    priority: priorityResult?.scores || null,
    ideaScores: ideaAnalysis?.scores || null,

    // Metadata
    metadata: {
      factoryId: "SF-01",
      version: "1.0",
      generatedAt: new Date().toISOString(),
      inputIdea: raw,
      category: ideaAnalysis?.category || "unknown",
    },
  };
}

/**
 * 生成 Executive Summary Markdown 报告。
 */
export function generateExecutiveSummary(pkg) {
  const es = pkg.executiveSummary || {};
  const ps = pkg.problemStatement || {};
  const tm = pkg.targetMarket || {};
  const bm = pkg.businessModel || {};
  const rm = pkg.revenueModel || {};
  const pv = pkg.productVision || {};
  const ra = pkg.riskAssessment || {};

  const formatB = (v) => v >= 1e9 ? `$${(v / 1e9).toFixed(1)}B` : `$${(v / 1e6).toFixed(0)}M`;

  const lines = [
    `# Product Strategy Package: ${es.title || "New Product"}`,
    "",
    "## Executive Summary",
    `- **Viability:** ${es.viabilityVerdict || "N/A"} (${es.viabilityScore || 0}/100)`,
    `- **Priority:** ${es.priorityLevel || "N/A"}`,
    `- **Recommendation:** ${es.recommendation || "N/A"}`,
    "",
    "## Problem Statement",
    `- **Who:** ${ps.who || "N/A"}`,
    `- **What:** ${ps.what || "N/A"}`,
    `- **Why:** ${ps.why || "N/A"}`,
    `- **Severity:** ${ps.severity || 0}/100`,
    "",
    "## Target Customer",
    `- **Segment:** ${pkg.targetCustomer?.segment || "N/A"}`,
    `- **Willingness to Pay:** ${pkg.targetCustomer?.willingnessToPay || 0}/100`,
    `- **Pain Points:** ${(pkg.targetCustomer?.painPoints || []).join(", ")}`,
    "",
    "## Target Market",
    `- **TAM:** ${formatB(tm.tam || 0)}`,
    `- **SAM:** ${formatB(tm.sam || 0)}`,
    `- **SOM:** ${formatB(tm.som || 0)}`,
    `- **Growth Rate:** ${tm.growthRate || 0}%`,
    "",
    "## Competitive Landscape",
    `- **Top 3 Market Share:** ${pkg.competitiveAnalysis?.top3Share || 0}%`,
    `- **Competition Intensity:** ${pkg.competitiveAnalysis?.landscape?.competitionIntensity || 50}/100`,
    "",
    "## Business Model",
    `- **Model:** ${bm?.type || "N/A"}`,
    `- **LTV/CAC:** ${bm?.ltvCacRatio || 0}x`,
    `- **Gross Margin:** ${bm?.grossMargin || 0}%`,
    `- **Year 1 Revenue:** $${rm?.year1Revenue?.toLocaleString() || 0}`,
    "",
    "## Product Vision",
    `- **Vision:** ${pv.vision || "N/A"}`,
    `- **Mission:** ${pv.mission || "N/A"}`,
    `- **North Star:** ${pkg.northStarMetric || "N/A"}`,
    "",
    "## Go-To-Market",
    `- **Entry:** ${pkg.gtmStrategy?.entryStrategy || "N/A"}`,
    `- **Time to Market:** ${pkg.gtmStrategy?.timeToMarketMonths || 0} months`,
    "",
    "## Risk Assessment",
    `- **Overall Risk:** ${ra.overallRisk || 50}/100`,
    `- **Market Risk:** ${ra.breakdown?.marketRisk || 50}/100`,
    `- **Tech Risk:** ${ra.breakdown?.techRisk || 50}/100`,
    "",
    "## Roadmap",
    `- **Total Duration:** ${pkg.roadmap?.totalDurationMonths || 0} months`,
    `- **Total Budget:** $${(pkg.roadmap?.totalBudget || 0).toLocaleString()}`,
    "",
    `---\n*Generated by SF-01 Product Strategy Factory at ${new Date().toISOString()}*`,
  ];

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

// ═══════════════════════════════════════════════════════
// Part L：Factory Integration
// ═══════════════════════════════════════════════════════

/**
 * SF-01 Factory 实现函数。
 *
 * 遵循 PR-36 Factory Contract：
 *   入参：FactoryInput
 *   出参：FactoryOutput
 *
 * @param {object} input — FactoryInput
 * @returns {object} FactoryOutput
 */
export function sf01ProductStrategyFactory(input) {
  const startTime = Date.now();
  const rawIdea = input?.parameters?.idea || input?.parameters?.raw || "";

  if (!rawIdea) {
    return createFactoryOutput({
      factoryId: "SF-01",
      status: "failed",
      error: "No product idea provided. Set parameters.idea or parameters.raw.",
    });
  }

  try {
    // 1. Idea Analysis
    const ideaAnalysis = analyzeProductIdea(rawIdea);

    // 2. Market Analysis
    const marketResult = analyzeMarket(ideaAnalysis);

    // 3. Competitor Analysis
    const competitorResult = analyzeCompetitors(ideaAnalysis);

    // 4. Business Model
    const businessModelResult = analyzeBusinessModel(ideaAnalysis, marketResult);

    // 5. Viability
    const viabilityResult = evaluateViability(ideaAnalysis, marketResult, competitorResult, businessModelResult);

    // 6. Prioritization
    const priorityResult = evaluatePriority(ideaAnalysis, viabilityResult);

    // 7. Vision
    const visionResult = generateVision(ideaAnalysis, marketResult);

    // 8. GTM
    const gtmResult = generateGTM(ideaAnalysis, marketResult, competitorResult, businessModelResult);

    // 9. Roadmap
    const roadmapResult = generateRoadmap(ideaAnalysis, viabilityResult);

    // 10. Strategy Package
    const pkg = createStrategyPackage({
      ideaAnalysis, marketResult, competitorResult,
      businessModelResult, viabilityResult, priorityResult,
      visionResult, gtmResult, roadmapResult,
    });

    // ── 构建 Artifacts ──
    const artifacts = [
      createFactoryArtifact({
        kind: "requirement",
        name: `Product Strategy: ${rawIdea}`,
        factoryId: "SF-01",
        content: generateExecutiveSummary(pkg),
        metadata: { artifactType: SF01_ARTIFACTS.STRATEGY_PACKAGE },
      }),
      createFactoryArtifact({
        kind: "report",
        name: "Market Analysis Report",
        factoryId: "SF-01",
        content: marketResult.report,
        metadata: { artifactType: SF01_ARTIFACTS.MARKET_ANALYSIS },
      }),
      createFactoryArtifact({
        kind: "report",
        name: "Competitor Report",
        factoryId: "SF-01",
        content: competitorResult.report,
        metadata: { artifactType: SF01_ARTIFACTS.COMPETITOR_REPORT },
      }),
      createFactoryArtifact({
        kind: "report",
        name: "Business Model Report",
        factoryId: "SF-01",
        content: businessModelResult.report,
        metadata: { artifactType: SF01_ARTIFACTS.BUSINESS_MODEL },
      }),
      createFactoryArtifact({
        kind: "report",
        name: "GTM Strategy Report",
        factoryId: "SF-01",
        content: gtmResult.report,
        metadata: { artifactType: SF01_ARTIFACTS.GTM_REPORT },
      }),
      createFactoryArtifact({
        kind: "report",
        name: "Product Roadmap Report",
        factoryId: "SF-01",
        content: roadmapResult.report,
        metadata: { artifactType: SF01_ARTIFACTS.ROADMAP_REPORT },
      }),
      createFactoryArtifact({
        kind: "report",
        name: "Product Viability Report",
        factoryId: "SF-01",
        content: `# Product Viability Report\n\n## Overall Score: ${viabilityResult.overall}/100\n\n**Verdict:** ${viabilityResult.verdict}\n\n${viabilityResult.recommendation}`,
        metadata: { artifactType: SF01_ARTIFACTS.VIABILITY_REPORT },
      }),
    ];

    // ── 构建 Metrics ──
    const metrics = [
      createFactoryMetric({ factoryId: "SF-01", name: "viability.score", value: viabilityResult.overall, kind: "score", unit: "pct" }),
      createFactoryMetric({ factoryId: "SF-01", name: "priority.score", value: priorityResult.weighted, kind: "score", unit: "pct" }),
      createFactoryMetric({ factoryId: "SF-01", name: "market.attractiveness", value: marketResult.attractivenessScore, kind: "score", unit: "pct" }),
      createFactoryMetric({ factoryId: "SF-01", name: "tam.billions", value: (ideaAnalysis.market?.tam || 0) / 1e9, kind: "money", unit: "B USD" }),
      createFactoryMetric({ factoryId: "SF-01", name: "competition.intensity", value: competitorResult.competitiveLandscape?.competitionIntensity || 50, kind: "score", unit: "pct" }),
      createFactoryMetric({ factoryId: "SF-01", name: "gross.margin", value: businessModelResult.model?.grossMargin || 0, kind: "percentage", unit: "%" }),
      createFactoryMetric({ factoryId: "SF-01", name: "duration.ms", value: Date.now() - startTime, kind: "duration", unit: "ms" }),
    ];

    return createFactoryOutput({
      factoryId: "SF-01",
      status: viabilityResult.overall >= 50 ? "passed" : "blocked",
      artifacts,
      metrics,
      decisions: [
        { title: "Viability Decision", description: `${viabilityResult.verdict} (${viabilityResult.overall}/100)`, score: viabilityResult.overall },
        { title: "Priority Decision", description: `${priorityResult.label}`, score: priorityResult.weighted },
        { title: "Business Model", description: businessModelResult.model?.type || "N/A", score: businessModelResult.recommendation?.score || 0 },
      ],
      nextActions: [
        priorityResult.level === PRIORITY_LEVEL.P0 || priorityResult.level === PRIORITY_LEVEL.P1
          ? "Proceed to SF-02 Requirement Engineering"
          : "Review strategy and gather more market validation",
        "Register all artifacts in SF-01 Artifact Graph",
        "Present Executive Summary to stakeholders",
      ],
      metadata: { category: ideaAnalysis.category, generatedAt: new Date().toISOString() },
    });
  } catch (err) {
    return createFactoryOutput({
      factoryId: "SF-01",
      status: "failed",
      error: `SF-01 analysis error: ${err.message}`,
      metrics: [createFactoryMetric({ factoryId: "SF-01", name: "duration.ms", value: Date.now() - startTime, kind: "duration", unit: "ms" })],
    });
  }
}

/**
 * 将 SF-01 注册到给定的 Factory Registry。
 *
 * @param {object} registry — PR-36 FactoryRegistry
 */
export function registerSF01(registry) {
  registry.registerImplementation("SF-01", sf01ProductStrategyFactory);
}

// ═══════════════════════════════════════════════════════
// Barrel Re-export
// ═══════════════════════════════════════════════════════

export {
  analyzeProductIdea,
  analyzeMarket,
  analyzeCompetitors,
  analyzeBusinessModel,
  evaluateViability,
  evaluatePriority,
  generateVision,
  generateGTM,
  generateRoadmap,
};

// ═══════════════════════════════════════════════════════
// Patch modules removed — runtime-verification, artifact-verification, mvp-enhancement, strategy-agent
// These were re-export only modules that added complexity without changing core pipeline output.
