/**
 * Ciena WaveServer / WaveLogic OEM Transceiver Catalog Seed
 *
 * Seeds Ciena-branded transceiver and coherent module PIDs for WaveServer,
 * WaveLogic 5e/5n open line system platforms and packet-optical equipment.
 *
 * Sources:
 *  - Ciena WaveServer 5 Product Overview (ciena.com)
 *  - Ciena WaveLogic 5e/5n Module Datasheet
 *  - Ciena Client Optics Portfolio Guide
 *
 * Run:  tsx packages/scraper/src/scrapers/ciena-waveserver-oem.ts
 * Cron: daily at 23:15
 */

import { pool, ensureVendor } from "../utils/db";

interface CienaWaveserverPID {
  pid: string;
  formFactor: string;
  speedGbps: number;
  speed: string;
  reachMeters: number;
  reachLabel: string;
  fiberType: string;
  connector: string;
  wavelengths?: string;
  standard?: string;
  category?: string;
  notes?: string;
}

const CIENA_WAVESERVER_PIDS: CienaWaveserverPID[] = [
  // ── 1G SFP Client ───────────────────────────────────────────────────────
  { pid: "SFP-10G-SR",           formFactor: "SFP+",    speedGbps: 10,  speed: "10G",  reachMeters: 300,     reachLabel: "SR",    fiberType: "MMF", connector: "LC",  wavelengths: "850nm",           standard: "10GBASE-SR" },
  { pid: "SFP-10G-LR",           formFactor: "SFP+",    speedGbps: 10,  speed: "10G",  reachMeters: 10000,   reachLabel: "LR",    fiberType: "SMF", connector: "LC",  wavelengths: "1310nm",          standard: "10GBASE-LR" },
  { pid: "SFP-10G-ER",           formFactor: "SFP+",    speedGbps: 10,  speed: "10G",  reachMeters: 40000,   reachLabel: "ER",    fiberType: "SMF", connector: "LC",  wavelengths: "1550nm",          standard: "10GBASE-ER" },
  { pid: "SFP-10G-ZR",           formFactor: "SFP+",    speedGbps: 10,  speed: "10G",  reachMeters: 80000,   reachLabel: "ZR",    fiberType: "SMF", connector: "LC",  wavelengths: "1550nm",          standard: "10GBASE-ZR" },

  // ── 10G SONET/SDH ────────────────────────────────────────────────────────
  { pid: "OC48-SFP",             formFactor: "SFP",     speedGbps: 2.5, speed: "OC48", reachMeters: 40000,   reachLabel: "LR",    fiberType: "SMF", connector: "LC",  wavelengths: "1310nm",          category: "Telecom", notes: "Ciena OC-48/STM-16 2.488G SFP" },
  { pid: "OC192-SFP",            formFactor: "SFP+",    speedGbps: 10,  speed: "OC192",reachMeters: 40000,   reachLabel: "LR",    fiberType: "SMF", connector: "LC",  wavelengths: "1310nm",          category: "Telecom", notes: "Ciena OC-192/STM-64 9.953G SFP+" },

  // ── 10G OTN ─────────────────────────────────────────────────────────────
  { pid: "SFP-OTU2-10G",         formFactor: "SFP+",    speedGbps: 10,  speed: "10G",  reachMeters: 40000,   reachLabel: "LR",    fiberType: "SMF", connector: "LC",  wavelengths: "1310nm",          category: "Telecom", notes: "Ciena OTU2 10.709G SFP+" },

  // ── 10G DWDM SFP+ ────────────────────────────────────────────────────────
  { pid: "DWDM-SFP10G-C-xx.x",  formFactor: "SFP+",    speedGbps: 10,  speed: "10G",  reachMeters: 80000,   reachLabel: "DWDM",  fiberType: "SMF", connector: "LC",  wavelengths: "C-band ITU DWDM", category: "Telecom", notes: "Ciena DWDM C-band 10G SFP+ (wavelength per order)" },

  // ── 25G SFP28 ────────────────────────────────────────────────────────────
  { pid: "XCVR-S10V",            formFactor: "SFP+",    speedGbps: 10,  speed: "10G",  reachMeters: 10000,   reachLabel: "LR",    fiberType: "SMF", connector: "LC",  wavelengths: "1310nm",          standard: "10GBASE-LR",  notes: "Ciena WaveServer client SFP+ 10G" },
  { pid: "XCVR-S28V",            formFactor: "SFP28",   speedGbps: 25,  speed: "25G",  reachMeters: 10000,   reachLabel: "LR",    fiberType: "SMF", connector: "LC",  wavelengths: "1310nm",          standard: "25GBASE-LR",  notes: "Ciena WaveServer client SFP28 25G" },

  // ── 40G QSFP+ ────────────────────────────────────────────────────────────
  { pid: "QSFP-40G-SR4",         formFactor: "QSFP+",   speedGbps: 40,  speed: "40G",  reachMeters: 150,     reachLabel: "SR4",   fiberType: "MMF", connector: "MPO", wavelengths: "850nm",           standard: "40GBASE-SR4" },
  { pid: "QSFP-40G-LR4",         formFactor: "QSFP+",   speedGbps: 40,  speed: "40G",  reachMeters: 10000,   reachLabel: "LR4",   fiberType: "SMF", connector: "LC",  wavelengths: "1295-1310nm",     standard: "40GBASE-LR4" },

  // ── 100G QSFP28 ──────────────────────────────────────────────────────────
  { pid: "XCVR-A00AQ4",          formFactor: "QSFP28",  speedGbps: 100, speed: "100G", reachMeters: 100,     reachLabel: "SR4",   fiberType: "MMF", connector: "MPO", wavelengths: "850nm",           standard: "100GBASE-SR4", notes: "Ciena WaveServer QSFP28 100G SR4" },
  { pid: "XCVR-A00BQ4",          formFactor: "QSFP28",  speedGbps: 100, speed: "100G", reachMeters: 10000,   reachLabel: "LR4",   fiberType: "SMF", connector: "LC",  wavelengths: "1295-1310nm",     standard: "100GBASE-LR4", notes: "Ciena WaveServer QSFP28 100G LR4" },
  { pid: "QSFP28-100G-ER4",      formFactor: "QSFP28",  speedGbps: 100, speed: "100G", reachMeters: 40000,   reachLabel: "ER4",   fiberType: "SMF", connector: "LC",  wavelengths: "1295-1310nm",     standard: "100GBASE-ER4" },

  // ── 100G CFP2 Coherent ───────────────────────────────────────────────────
  { pid: "CFP2-ACO-100G",        formFactor: "CFP2",    speedGbps: 100, speed: "100G", reachMeters: 1000000, reachLabel: "ACO",   fiberType: "SMF", connector: "LC",  wavelengths: "C-band",          category: "Telecom", notes: "Ciena 100G CFP2 Analogue Coherent Optics" },
  { pid: "CFP2-DCO-200G",        formFactor: "CFP2",    speedGbps: 200, speed: "200G", reachMeters: 1500000, reachLabel: "DCO",   fiberType: "SMF", connector: "LC",  wavelengths: "C-band",          category: "Telecom", notes: "Ciena 200G CFP2 Digital Coherent Optics" },

  // ── 100G CFP OTN ─────────────────────────────────────────────────────────
  { pid: "CFP-OTU4-100G",        formFactor: "CFP",     speedGbps: 100, speed: "100G", reachMeters: 40000,   reachLabel: "LR4",   fiberType: "SMF", connector: "LC",  wavelengths: "1295-1310nm",     category: "Telecom", notes: "Ciena OTU4 100G CFP LR4" },

  // ── WaveLogic 5 Coherent Line Modules ────────────────────────────────────
  { pid: "WL5e-SEQ",             formFactor: "QSFP-DD", speedGbps: 400, speed: "400G", reachMeters: 3000000, reachLabel: "WL5e",  fiberType: "SMF", connector: "LC",  wavelengths: "C-band",          category: "Telecom", notes: "Ciena WaveLogic 5e coherent 400G-800G QSFP-DD" },
  { pid: "WL5n-SEQ",             formFactor: "QSFP-DD", speedGbps: 200, speed: "200G", reachMeters: 3000000, reachLabel: "WL5n",  fiberType: "SMF", connector: "LC",  wavelengths: "C-band",          category: "Telecom", notes: "Ciena WaveLogic 5 nano coherent QSFP-DD" },

  // ── 400G QSFP-DD Client ──────────────────────────────────────────────────
  { pid: "XCVR-B00DPP",          formFactor: "QSFP-DD", speedGbps: 400, speed: "400G", reachMeters: 2000,    reachLabel: "DR4",   fiberType: "SMF", connector: "MPO", wavelengths: "1310nm",          standard: "400GBASE-DR4", notes: "Ciena WaveServer QSFP-DD 400G DR4" },
  { pid: "QSFP-DD-ZR-400G",      formFactor: "QSFP-DD", speedGbps: 400, speed: "400G", reachMeters: 120000,  reachLabel: "ZR",    fiberType: "SMF", connector: "LC",  wavelengths: "C-band",          category: "Telecom", standard: "400ZR", notes: "Ciena 400G ZR coherent QSFP-DD" },
];

// PIDs that use 'Telecom' category (coherent/OTN/SONET/DWDM)
const TELECOM_PIDS = new Set([
  "OC48-SFP",
  "OC192-SFP",
  "SFP-OTU2-10G",
  "DWDM-SFP10G-C-xx.x",
  "CFP2-ACO-100G",
  "CFP2-DCO-200G",
  "CFP-OTU4-100G",
  "WL5e-SEQ",
  "WL5n-SEQ",
  "QSFP-DD-ZR-400G",
]);

export async function scrapeCienaWaveserverOem(): Promise<void> {
  console.log("=== Ciena WaveServer/WaveLogic OEM Transceiver Seed ===\n");

  const vendorId = await ensureVendor(
    "Ciena",
    "oem",
    "https://www.ciena.com",
    undefined
  );

  let inserted = 0;
  let updated  = 0;
  let errors   = 0;

  for (const p of CIENA_WAVESERVER_PIDS) {
    const slug     = `ciena-ws-${p.pid.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
    const category = p.category ?? (TELECOM_PIDS.has(p.pid) ? "Telecom" : "DataCenter");
    try {
      const res = await pool.query(
        `INSERT INTO transceivers
           (slug, part_number, vendor_id, form_factor, speed, speed_gbps,
            reach_meters, reach_label, fiber_type, connector, wavelengths,
            dom_support, ieee_reference, market_status, category, notes)
         VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,true,$12,'Mainstream',$13,$14)
         ON CONFLICT (slug) DO UPDATE SET
           speed_gbps   = EXCLUDED.speed_gbps,
           reach_meters = CASE WHEN EXCLUDED.reach_meters > 0 THEN EXCLUDED.reach_meters ELSE transceivers.reach_meters END,
           fiber_type   = CASE WHEN EXCLUDED.fiber_type <> '' THEN EXCLUDED.fiber_type ELSE transceivers.fiber_type END,
           wavelengths  = COALESCE(EXCLUDED.wavelengths, transceivers.wavelengths),
           updated_at   = NOW()
         RETURNING (xmax = 0) as was_inserted`,
        [slug, p.pid, vendorId, p.formFactor, p.speed, p.speedGbps,
         p.reachMeters, p.reachLabel, p.fiberType, p.connector,
         p.wavelengths ?? null, p.standard ?? null, category, p.notes ?? null]
      );
      if (res.rows[0]?.was_inserted) inserted++; else updated++;
    } catch (err) {
      console.warn(`  Skip ${p.pid}: ${(err as Error).message.slice(0, 80)}`);
      errors++;
    }
  }

  console.log(`\n=== Ciena WaveServer/WaveLogic OEM Seed Complete ===`);
  console.log(`  Inserted: ${inserted}`);
  console.log(`  Updated:  ${updated}`);
  console.log(`  Errors:   ${errors}`);
  console.log(`  Total PIDs: ${CIENA_WAVESERVER_PIDS.length}\n`);
}

if (require.main === module) {
  scrapeCienaWaveserverOem()
    .then(() => pool.end())
    .catch((err) => {
      console.error("Fatal:", err);
      pool.end();
      process.exit(1);
    });
}
