/**
 * Seed faq_embeddings and troubleshooting_embeddings from built-in knowledge.
 *
 * Since we don't have a FAQ table yet, this seeds from a curated set of
 * transceiver FAQ entries and troubleshooting guides based on Flexoptix
 * domain expertise.
 *
 * Run: npx tsx packages/api/src/embeddings/seed-faq.ts
 */
import { embed, upsertPoints } from "./client";
import { randomUUID } from "crypto";

interface FaqEntry {
  question: string;
  answer: string;
  category: string;
  tags: string[];
}

interface TroubleshootingEntry {
  symptom: string;
  cause: string;
  solution: string;
  category: string;
  severity: "low" | "medium" | "high" | "critical";
}

const FAQ_ENTRIES: FaqEntry[] = [
  // Form Factor FAQs
  {
    question: "What is the difference between SFP, SFP+, and SFP28?",
    answer: "SFP supports up to 1Gbps, SFP+ supports up to 10Gbps, and SFP28 supports up to 25Gbps. They share the same physical form factor but differ in electrical interface speed. SFP+ and SFP28 are backward compatible with SFP ports at reduced speeds.",
    category: "form_factor",
    tags: ["SFP", "SFP+", "SFP28", "compatibility"],
  },
  {
    question: "What is the difference between QSFP+ and QSFP28?",
    answer: "QSFP+ supports 4x10G = 40Gbps, while QSFP28 supports 4x25G = 100Gbps. Both use the same physical form factor. QSFP28 is backward compatible with QSFP+ ports. QSFP28 can also be used in breakout mode (4x25G).",
    category: "form_factor",
    tags: ["QSFP+", "QSFP28", "40G", "100G", "breakout"],
  },
  {
    question: "What is QSFP-DD and how does it differ from QSFP28?",
    answer: "QSFP-DD (Double Density) has 8 lanes instead of 4, supporting up to 400G (8x50G) or 800G (8x100G). It is backward compatible with QSFP28 modules. The 'DD' refers to the doubled electrical lane count.",
    category: "form_factor",
    tags: ["QSFP-DD", "400G", "800G"],
  },
  {
    question: "What is OSFP and when should I use it?",
    answer: "OSFP (Octal Small Form Factor Pluggable) is designed for 400G and 800G applications. It has 8 electrical lanes and better thermal performance than QSFP-DD due to its slightly larger size. OSFP is preferred for high-power coherent optics and 800G deployments.",
    category: "form_factor",
    tags: ["OSFP", "400G", "800G", "coherent"],
  },
  {
    question: "What is CFP2-DCO?",
    answer: "CFP2-DCO is a coherent Digital Coherent Optic transceiver in CFP2 form factor. It supports 100G-400G coherent transmission over long distances (hundreds to thousands of km). DCO includes the DSP (Digital Signal Processor) inside the module.",
    category: "form_factor",
    tags: ["CFP2", "DCO", "coherent", "long-haul"],
  },

  // Fiber Type FAQs
  {
    question: "What is the difference between single-mode and multi-mode fiber?",
    answer: "Single-mode fiber (SMF, 9/125µm) carries one light mode and supports distances up to 80km+ at higher cost. Multi-mode fiber (MMF, 50/125µm OM3/OM4/OM5) carries multiple light modes, supports up to 300-400m, and is cheaper. Use SMF for campus/metro/long-haul, MMF for intra-building/data center.",
    category: "fiber",
    tags: ["SMF", "MMF", "single-mode", "multi-mode", "OM3", "OM4"],
  },
  {
    question: "What do OM3, OM4, and OM5 mean?",
    answer: "OM3, OM4, and OM5 are multi-mode fiber grades. OM3 supports 10G up to 300m, OM4 supports 10G up to 400m, and OM5 supports SWDM (Shortwave Division Multiplexing) for 40G/100G over longer distances. OM5 is also called WBMMF (Wideband Multi-Mode Fiber).",
    category: "fiber",
    tags: ["OM3", "OM4", "OM5", "multi-mode", "SWDM"],
  },

  // Reach & Distance FAQs
  {
    question: "What do SR, LR, ER, and ZR mean in transceiver names?",
    answer: "SR = Short Reach (up to 300-400m, typically multi-mode). LR = Long Reach (up to 10km, single-mode). ER = Extended Reach (up to 40km, single-mode). ZR = Very Long Reach (up to 80km+, single-mode). These are IEEE/MSA standard designations.",
    category: "reach",
    tags: ["SR", "LR", "ER", "ZR", "reach", "distance"],
  },
  {
    question: "What is the maximum distance for a 100G-LR4 transceiver?",
    answer: "100G-LR4 supports up to 10km over single-mode fiber using 4 wavelengths (1295.56nm, 1300.05nm, 1304.58nm, 1309.14nm) with CWDM4 technology. It uses a duplex LC connector.",
    category: "reach",
    tags: ["100G", "LR4", "10km", "CWDM4"],
  },

  // Compatibility FAQs
  {
    question: "Can I use third-party transceivers in Cisco switches?",
    answer: "Yes, but Cisco switches may show warnings for non-Cisco-branded optics. Use 'service unsupported-transceiver' command to suppress warnings. Third-party compatible transceivers (like Flexoptix) are programmed with Cisco-compatible coding and work identically. Always verify the specific switch model and IOS version.",
    category: "compatibility",
    tags: ["Cisco", "third-party", "compatible", "coding"],
  },
  {
    question: "What is transceiver coding and why does it matter?",
    answer: "Transceiver coding refers to the EEPROM data programmed into the SFP/QSFP module that identifies it to the switch. Vendor-locked switches check this data and may reject uncoded or incorrectly coded optics. Flexoptix FlexBox can reprogram coding for any vendor.",
    category: "compatibility",
    tags: ["coding", "EEPROM", "FlexBox", "vendor-lock"],
  },
  {
    question: "How do breakout cables work with QSFP28?",
    answer: "A QSFP28 breakout cable splits one 100G QSFP28 port into 4x25G SFP28 connections using a DAC or AOC cable. This requires the switch to support breakout mode. Common breakout configurations: QSFP28 to 4xSFP28, QSFP-DD to 2xQSFP28, OSFP to 2xQSFP28.",
    category: "compatibility",
    tags: ["breakout", "QSFP28", "SFP28", "DAC", "AOC"],
  },

  // WDM FAQs
  {
    question: "What is the difference between CWDM and DWDM?",
    answer: "CWDM (Coarse WDM) uses wider channel spacing (20nm), supports up to 18 channels, and is cheaper but limited to shorter distances. DWDM (Dense WDM) uses narrow spacing (0.8nm/100GHz or 0.4nm/50GHz), supports 40-96+ channels, and enables long-haul with amplification (EDFA).",
    category: "wdm",
    tags: ["CWDM", "DWDM", "WDM", "wavelength"],
  },
  {
    question: "What is 400ZR?",
    answer: "400ZR is an OIF standard for 400G coherent DWDM transmission in QSFP-DD or OSFP form factor. It supports up to 120km over a single wavelength using 16QAM modulation. It enables point-to-point DCI (Data Center Interconnect) without external transponders.",
    category: "wdm",
    tags: ["400ZR", "coherent", "DCI", "DWDM", "OIF"],
  },

  // Power & Temperature FAQs
  {
    question: "What is the typical power consumption of different transceivers?",
    answer: "SFP/SFP+: 0.7-1.5W. SFP28: 1-2W. QSFP+: 1.5-3.5W. QSFP28: 2.5-5W. QSFP-DD 400G: 12-15W. OSFP 400G: 15-20W. Coherent (CFP2-DCO): 20-25W. 800G OSFP: 20-30W. Higher speeds and longer reach generally require more power.",
    category: "power",
    tags: ["power", "watts", "thermal"],
  },
  {
    question: "What temperature ranges do transceivers support?",
    answer: "Commercial (COM): 0°C to 70°C — standard data center use. Extended (EXT): -5°C to 85°C — outdoor/harsh environments. Industrial (IND): -40°C to 85°C — extreme conditions. Most data center transceivers are COM rated.",
    category: "power",
    tags: ["temperature", "commercial", "industrial", "extended"],
  },

  // Market & Technology FAQs
  {
    question: "What is CPO (Co-Packaged Optics)?",
    answer: "CPO integrates optical transceivers directly into the switch ASIC package, eliminating the pluggable module. This reduces power consumption (30-50% less), latency, and cost at scale. CPO is expected for 1.6T+ speeds but is still in development. Current approach is mostly pluggable (OSFP/QSFP-DD).",
    category: "technology",
    tags: ["CPO", "co-packaged", "1.6T", "future"],
  },
  {
    question: "What is LPO (Linear Pluggable Optics)?",
    answer: "LPO removes the DSP/retimer from the transceiver module, reducing power and cost by ~30%. It requires clean signal paths and shorter reach. LPO works for intra-rack connections (<2m) where signal integrity is sufficient. Currently in early adoption with limited vendor support.",
    category: "technology",
    tags: ["LPO", "linear", "power-saving"],
  },
  {
    question: "When will 800G transceivers be mainstream?",
    answer: "800G OSFP/QSFP-DD800 transceivers are available since 2024 from vendors like Innolight, Coherent, and Broadcom. Mass adoption is expected 2025-2026 as switch ASICs (Broadcom Tomahawk 5, 51.2T) support native 800G ports. AI/ML data centers are the primary early adopters.",
    category: "technology",
    tags: ["800G", "OSFP", "Tomahawk", "AI"],
  },
];

const TROUBLESHOOTING_ENTRIES: TroubleshootingEntry[] = [
  {
    symptom: "Transceiver not recognized by switch — port shows 'not present' or 'unsupported'",
    cause: "Incorrect transceiver coding (EEPROM vendor ID doesn't match switch vendor), or module is not compatible with the switch platform/IOS version.",
    solution: "1. Check switch vendor compatibility list. 2. Verify transceiver coding matches the switch vendor. 3. For Cisco: use 'service unsupported-transceiver' command. 4. Try reseating the module. 5. Use Flexoptix FlexBox to recode if needed.",
    category: "recognition",
    severity: "high",
  },
  {
    symptom: "Link is up but experiencing high bit error rate (BER) or CRC errors",
    cause: "Dirty fiber connector, fiber bend radius exceeded, incorrect fiber type (SMF vs MMF mismatch), or transceiver power levels out of spec.",
    solution: "1. Clean fiber connectors with IPA wipes. 2. Check fiber type matches transceiver (SMF for LR, MMF for SR). 3. Use OTDR to test fiber. 4. Check optical power levels via 'show interface transceiver' — should be within Rx sensitivity range. 5. Replace patch cable.",
    category: "performance",
    severity: "high",
  },
  {
    symptom: "Transceiver overheating — temperature alarm triggered",
    cause: "Insufficient airflow in switch chassis, failed fan module, ambient temperature too high, or transceiver power consumption exceeds port thermal budget.",
    solution: "1. Check fan module status. 2. Verify ambient temperature is within transceiver spec (usually 0-70°C COM). 3. Ensure proper airflow — no blocked vents. 4. Consider lower-power transceiver variant. 5. For high-power modules (>15W), verify switch supports the thermal requirement.",
    category: "thermal",
    severity: "critical",
  },
  {
    symptom: "Link flapping — port goes up and down repeatedly",
    cause: "Marginal optical power (near Rx sensitivity threshold), loose connector, faulty transceiver, or auto-negotiation mismatch.",
    solution: "1. Check optical power — if near sensitivity threshold, clean connectors or shorten fiber. 2. Verify both ends have matching speed/duplex settings. 3. Try a different transceiver. 4. Check for fiber micro-bends. 5. Disable auto-negotiation if both ends are configured correctly.",
    category: "connectivity",
    severity: "high",
  },
  {
    symptom: "Low transmit (Tx) power from transceiver",
    cause: "Aging laser, transceiver damage, or operating at edge of temperature range.",
    solution: "1. Compare Tx power with datasheet spec — if below minimum, replace transceiver. 2. Check operating temperature. 3. Try module in different port to rule out port issue. 4. If within spec but link still fails, the fiber path may have too much loss — check with OTDR.",
    category: "optical",
    severity: "medium",
  },
  {
    symptom: "QSFP28 breakout mode not working — 4x25G ports not appearing",
    cause: "Switch doesn't support breakout on that port, breakout not configured, or breakout cable is faulty.",
    solution: "1. Verify switch model supports breakout mode on the specific port. 2. Configure breakout: Cisco 'interface breakout module X port Y map 25g-4x'. 3. Save config and reload if required. 4. Check cable — must be a breakout DAC/AOC, not a trunk cable.",
    category: "breakout",
    severity: "medium",
  },
  {
    symptom: "DOM (Digital Optical Monitoring) values not showing",
    cause: "Transceiver doesn't support DOM, switch firmware too old, or DOM threshold monitoring not enabled.",
    solution: "1. Verify transceiver supports DDM/DOM (check datasheet). 2. Use 'show interface transceiver detail' or equivalent command. 3. Update switch firmware if DOM is supported but not displayed. 4. Some third-party optics may not report all DOM fields.",
    category: "monitoring",
    severity: "low",
  },
  {
    symptom: "100G link working but only at 40G speed",
    cause: "QSFP28 module inserted into QSFP+ port, or port speed configured to 40G instead of 100G.",
    solution: "1. Verify the port supports 100G (QSFP28). 2. Check port speed configuration — set to 100G explicitly. 3. Verify both ends are using QSFP28 (not QSFP+) transceivers. 4. QSFP28 is backward compatible and will auto-negotiate to 40G in QSFP+ ports.",
    category: "speed",
    severity: "medium",
  },
  {
    symptom: "Coherent transceiver (400ZR/ZR+) not establishing link",
    cause: "Wavelength mismatch between endpoints, incorrect modulation format, chromatic dispersion exceeds module tolerance, or OSNR too low.",
    solution: "1. Verify both ends use the same wavelength channel. 2. Check modulation format matches (16QAM for 400ZR). 3. Measure OSNR — must be >20dB for 400ZR. 4. Check fiber distance doesn't exceed 120km (400ZR spec). 5. For ZR+, verify amplifier placement.",
    category: "coherent",
    severity: "high",
  },
  {
    symptom: "Transceiver works in one switch but not another of the same model",
    cause: "Different firmware versions, different port capabilities, or intermittent hardware issue with the transceiver.",
    solution: "1. Compare firmware versions on both switches. 2. Try the same port number on both switches. 3. Clean the transceiver contacts with IPA. 4. Check for bent pins in the switch port cage. 5. If the issue persists, the transceiver may have marginal soldering — try a replacement.",
    category: "compatibility",
    severity: "medium",
  },
];

async function main() {
  console.log("=== Seeding FAQ + Troubleshooting Embeddings ===\n");

  // Seed FAQs
  console.log(`Embedding ${FAQ_ENTRIES.length} FAQ entries...\n`);
  const BATCH_SIZE = 5;
  let faqTotal = 0;

  for (let i = 0; i < FAQ_ENTRIES.length; i += BATCH_SIZE) {
    const batch = FAQ_ENTRIES.slice(i, i + BATCH_SIZE);
    const points = await Promise.all(
      batch.map(async (entry) => {
        const text = `Q: ${entry.question}\nA: ${entry.answer}`;
        const vector = await embed(text);
        return {
          id: randomUUID(),
          vector,
          payload: {
            question: entry.question,
            answer: entry.answer,
            category: entry.category,
            tags: entry.tags.join(", "),
            text,
          },
        };
      }),
    );

    await upsertPoints("faq_embeddings", points);
    faqTotal += points.length;
    console.log(`  FAQ: ${faqTotal}/${FAQ_ENTRIES.length}`);
  }

  // Seed Troubleshooting
  console.log(`\nEmbedding ${TROUBLESHOOTING_ENTRIES.length} troubleshooting entries...\n`);
  let tsTotal = 0;

  for (let i = 0; i < TROUBLESHOOTING_ENTRIES.length; i += BATCH_SIZE) {
    const batch = TROUBLESHOOTING_ENTRIES.slice(i, i + BATCH_SIZE);
    const points = await Promise.all(
      batch.map(async (entry) => {
        const text = `Symptom: ${entry.symptom}\nCause: ${entry.cause}\nSolution: ${entry.solution}`;
        const vector = await embed(text);
        return {
          id: randomUUID(),
          vector,
          payload: {
            symptom: entry.symptom,
            cause: entry.cause,
            solution: entry.solution,
            category: entry.category,
            severity: entry.severity,
            text,
          },
        };
      }),
    );

    await upsertPoints("troubleshooting_embeddings", points);
    tsTotal += points.length;
    console.log(`  Troubleshooting: ${tsTotal}/${TROUBLESHOOTING_ENTRIES.length}`);
  }

  console.log(`\n=== Done: ${faqTotal} FAQs + ${tsTotal} troubleshooting entries ===`);
}

main().catch((err) => {
  console.error("Fatal:", err);
  process.exit(1);
});
