/**
 * WS7: Path of Adoption & Implementation Roadmap
 */
import { Router } from "express";
import { computeAllHypeCycles, computeHypeCycle, findTechnology, TECH_GENERATIONS } from "../hype-cycle/norton-bass";

export const adoptionRouter = Router();

const MIGRATION_PATHS: Record<string, { from: string; to: string; steps: string[]; timeline_months: number; risk: string }[]> = {
  "1G SFP": [{ from: "1G SFP", to: "10G SFP+", steps: ["Verify switch SFP+ port availability", "Order SFP+ transceivers", "Replace SFP modules during maintenance window", "Update monitoring thresholds"], timeline_months: 2, risk: "Low — drop-in replacement in most cases" }],
  "10G SFP+": [{ from: "10G SFP+", to: "25G SFP28", steps: ["Verify SFP28 port compatibility (same cage)", "Check NIC support (25G capable)", "Order SFP28 transceivers", "Swap during maintenance", "Update interface speed config"], timeline_months: 3, risk: "Low — SFP28 backward compatible with SFP+ cage" }],
  "25G SFP28": [{ from: "25G SFP28", to: "100G QSFP28", steps: ["Plan QSFP28 leaf-spine topology", "Order new QSFP28 switches if needed", "Deploy 100G spine first", "Migrate leaf uplinks to QSFP28", "Use 4×25G breakout cables for transition"], timeline_months: 6, risk: "Medium — requires topology changes" }],
  "40G QSFP+": [{ from: "40G QSFP+", to: "100G QSFP28", steps: ["QSFP28 is backward compatible with QSFP+ cage", "Order QSFP28 transceivers", "Swap QSFP+ for QSFP28 per port", "Update port speed configuration", "Verify optic DOM readings"], timeline_months: 3, risk: "Low — same cage, same fiber" }],
  "100G QSFP28": [
    { from: "100G QSFP28", to: "400G QSFP-DD", steps: ["Plan 400G spine deployment", "Evaluate QSFP-DD switches (Arista 7060X5, Cisco N9K-C9364D)", "Deploy 400G spine alongside 100G", "Migrate leaf uplinks using 4×100G breakout", "Replace 100G leaf switches over 12 months"], timeline_months: 12, risk: "Medium — new switches needed, but breakout eases transition" },
    { from: "100G QSFP28", to: "400G OSFP", steps: ["Same as QSFP-DD path but with OSFP switches", "Consider thermal requirements (OSFP runs cooler)", "Check rack compatibility"], timeline_months: 12, risk: "Medium — OSFP cages not backward compatible with QSFP" }
  ],
  "400G QSFP-DD": [{ from: "400G QSFP-DD", to: "800G QSFP-DD800", steps: ["Evaluate QSFP-DD800 switch availability", "QSFP-DD800 is backward compatible with QSFP-DD", "Deploy 800G spine for AI/ML clusters first", "Use 2×400G breakout for initial migration", "Full 800G deployment as prices normalize"], timeline_months: 18, risk: "Medium-High — early adoption, limited vendor choice" }],
};

/**
 * GET /api/adoption
 * Full technology roadmap with adoption phases
 */
adoptionRouter.get("/", async (_req, res) => {
  try {
    const year = new Date().getFullYear();
    const allCycles = computeAllHypeCycles(year);

    const roadmap = allCycles.map(h => {
      const tech = TECH_GENERATIONS.find(t => t.name === h.technology);
      const migrations = MIGRATION_PATHS[h.technology] || [];

      return {
        technology: h.technology,
        speed_gbps: tech?.speedGbps,
        form_factor: tech?.formFactor,
        intro_year: tech?.introYear,
        peak_year: tech?.peakYear,
        phase: h.phase,
        position_pct: h.positionPct,
        adoption_pct: h.adoptionPct,
        maturity: getMaturityIndicators(h.phase, h.adoptionPct),
        migration_paths: migrations,
        recommendation: getRecommendation(h.phase, h.technology),
      };
    }).sort((a, b) => (b.speed_gbps || 0) - (a.speed_gbps || 0));

    res.json({ roadmap, year });
  } catch (err) {
    console.error("Adoption roadmap error:", err);
    res.status(500).json({ error: "Internal server error" });
  }
});

/**
 * GET /api/adoption/:technology
 * Detailed adoption analysis for one technology
 */
adoptionRouter.get("/:technology", async (req, res) => {
  try {
    const tech = findTechnology(req.params.technology);
    if (!tech) return res.status(404).json({ error: "Technology not found", available: TECH_GENERATIONS.map(t => t.name) });

    const year = new Date().getFullYear();
    const hype = computeHypeCycle(tech, year);
    const migrations = MIGRATION_PATHS[tech.name] || [];

    res.json({
      technology: tech.name,
      speed_gbps: tech.speedGbps,
      form_factor: tech.formFactor,
      intro_year: tech.introYear,
      peak_year: tech.peakYear,
      hype_cycle: {
        phase: hype.phase,
        position_pct: hype.positionPct,
        adoption_pct: hype.adoptionPct,
        forecast: hype.forecast,
      },
      maturity: getMaturityIndicators(hype.phase, hype.adoptionPct),
      migration_paths: migrations,
      recommendation: getRecommendation(hype.phase, tech.name),
      implementation_timeline: getImplementationTimeline(tech.name, hype.phase),
      risks: getRiskAssessment(hype.phase, tech.name),
    });
  } catch (err) {
    res.status(500).json({ error: "Internal server error" });
  }
});

function getMaturityIndicators(phase: string, adoptionPct: number) {
  const indicators: Record<string, string> = {};
  if (adoptionPct > 80) {
    indicators.driver_support = "Universal — all major OS versions";
    indicators.interop = "Excellent — plug-and-play across vendors";
    indicators.supply = "Abundant — multiple factories, short lead times";
    indicators.ecosystem = "Mature — extensive documentation, training available";
  } else if (adoptionPct > 50) {
    indicators.driver_support = "Good — latest OS versions, some legacy gaps";
    indicators.interop = "Good — tested across major vendors, edge cases exist";
    indicators.supply = "Stable — 3-6 week lead times typical";
    indicators.ecosystem = "Growing — vendor support responsive, community active";
  } else if (adoptionPct > 20) {
    indicators.driver_support = "Limited — requires specific firmware versions";
    indicators.interop = "Developing — test before deploying, vendor-specific quirks";
    indicators.supply = "Constrained — 8-16 week lead times, allocation possible";
    indicators.ecosystem = "Early — limited documentation, vendor engineering support needed";
  } else {
    indicators.driver_support = "Bleeding edge — beta firmware, limited NOS support";
    indicators.interop = "Minimal — lab testing required, expect issues";
    indicators.supply = "Scarce — sampling/pre-order only, long lead times";
    indicators.ecosystem = "Nascent — standards still evolving, few reference designs";
  }
  return indicators;
}

function getRecommendation(phase: string, tech: string): string {
  switch (phase) {
    case "PLATEAU_OF_PRODUCTIVITY": return `${tech} is fully mature. Deploy confidently. Focus on cost optimization and vendor consolidation.`;
    case "SLOPE_OF_ENLIGHTENMENT": return `${tech} is the sweet spot for deployment. Proven reliability, falling prices, growing ecosystem. Recommended for new deployments.`;
    case "TROUGH_OF_DISILLUSIONMENT": return `${tech} is in the trough — prices dropping but some early adopters had interop issues. Good time to buy at discount if you can handle minor quirks.`;
    case "PEAK_OF_INFLATED_EXPECTATIONS": return `${tech} is overhyped. Only deploy if you have a specific use case requiring it. Expect premium pricing and potential supply constraints.`;
    case "INNOVATION_TRIGGER": return `${tech} is emerging technology. Evaluate in lab only. Do NOT deploy in production. Wait for standards ratification and ecosystem development.`;
    default: return `${tech} is in legacy phase. Plan migration to next generation.`;
  }
}

function getImplementationTimeline(tech: string, phase: string) {
  return {
    evaluation: phase === "INNOVATION_TRIGGER" ? "3-6 months" : "2-4 weeks",
    lab_testing: phase === "INNOVATION_TRIGGER" ? "3-6 months" : "2-4 weeks",
    pilot_deployment: "1-3 months",
    production_rollout: "3-12 months depending on scale",
    full_migration: "6-18 months",
    total_estimated: phase === "PLATEAU_OF_PRODUCTIVITY" ? "3-6 months" :
                     phase === "SLOPE_OF_ENLIGHTENMENT" ? "6-12 months" :
                     phase === "TROUGH_OF_DISILLUSIONMENT" ? "9-15 months" : "12-24 months",
  };
}

function getRiskAssessment(phase: string, tech: string) {
  return {
    technology_risk: phase === "INNOVATION_TRIGGER" ? "High — standards incomplete, firmware bugs likely" :
                     phase === "PEAK_OF_INFLATED_EXPECTATIONS" ? "Medium — standards ratified but early silicon" :
                     "Low — proven technology, stable implementations",
    supply_risk: phase === "INNOVATION_TRIGGER" ? "High — limited fab capacity, allocation" :
                 phase === "PEAK_OF_INFLATED_EXPECTATIONS" ? "Medium — demand may exceed supply at peak" :
                 "Low — multiple suppliers, established supply chains",
    vendor_lock_in: "Low — Flexoptix FlexBox coding eliminates vendor lock-in for transceivers",
    interop_risk: phase === "INNOVATION_TRIGGER" ? "High — expect vendor-specific issues" :
                  phase === "PEAK_OF_INFLATED_EXPECTATIONS" ? "Medium — test thoroughly before deployment" :
                  "Low — broadly tested interoperability",
  };
}
