/**
 * Ribbon Communications OEM Transceiver Catalog Seed
 *
 * Seeds Ribbon Communications branded transceiver PIDs for SBC (Session
 * Border Controller), Apollo IP/Optical, and SPB series platforms.
 * Includes SONET OC-3/12/48 optics inherited from the SONUS/GENBAND/ECI lineage,
 * plus DWDM and CFP2 coherent modules for the optical transport portfolio.
 *
 * Sources:
 *  - Ribbon Communications Hardware Catalog (ribboncommunications.com)
 *  - Ribbon SBC 5110/5210/7000 Series Hardware Guide
 *  - Ribbon Apollo 9400/9500 IP/Optical Platform Reference
 *  - Telcordia GR-253-CORE SONET specifications
 *
 * Run:  tsx packages/scraper/src/scrapers/ribbon-comms-oem.ts
 * Cron: daily at 22:45
 */

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

interface RibbonCommsPID {
  pid: string;
  formFactor: string;
  speedGbps: number;
  speed: string;
  reachMeters: number;
  reachLabel: string;
  fiberType: string;
  connector: string;
  wavelengths?: string;
  standard?: string;
  notes?: string;
  isTelecom?: boolean;
}

const RIBBON_COMMS_PIDS: RibbonCommsPID[] = [
  // ── 1G SFP (SBC access / management ports) ──────────────────────────────
  { pid: "SFP-GE-SX",        formFactor: "SFP",   speedGbps: 1,   speed: "1G",    reachMeters: 550,    reachLabel: "SX",       fiberType: "MMF", connector: "LC",   wavelengths: "850nm",       standard: "1000BASE-SX" },
  { pid: "SFP-GE-LX",        formFactor: "SFP",   speedGbps: 1,   speed: "1G",    reachMeters: 10000,  reachLabel: "LX",       fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",      standard: "1000BASE-LX" },
  { pid: "SFP-GE-T",         formFactor: "SFP",   speedGbps: 1,   speed: "1G",    reachMeters: 100,    reachLabel: "T",        fiberType: "DAC", connector: "RJ45",                             standard: "1000BASE-T" },
  { pid: "SFP-GE-BIDI-1310", formFactor: "SFP",   speedGbps: 1,   speed: "1G",    reachMeters: 10000,  reachLabel: "BiDi",     fiberType: "SMF", connector: "LC",   wavelengths: "1310/1490nm", notes: "1G BiDi single-fiber for SBC 5110 management" },

  // ── 10G SFP+ (SBC media / trunk ports) ──────────────────────────────────
  { 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",  notes: "10G ZR 80km for long-haul SBC inter-site trunks" },
  { pid: "SFP-10G-LR-S",     formFactor: "SFP+",  speedGbps: 10,  speed: "10G",   reachMeters: 10000,  reachLabel: "LR-S",     fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",      notes: "10G LR industrial temp for outdoor SBC deployments" },

  // ── 25G SFP28 ────────────────────────────────────────────────────────────
  { pid: "SFP-25G-LR",       formFactor: "SFP28", speedGbps: 25,  speed: "25G",   reachMeters: 10000,  reachLabel: "LR",       fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",      standard: "25GBASE-LR" },

  // ── 40G / 100G (Apollo 9400 uplinks) ─────────────────────────────────────
  { pid: "QSFP-40G-LR4",     formFactor: "QSFP+", speedGbps: 40,  speed: "40G",   reachMeters: 10000,  reachLabel: "LR4",      fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",      standard: "40GBASE-LR4" },
  { pid: "QSFP-100G-LR4",    formFactor: "QSFP28",speedGbps: 100, speed: "100G",  reachMeters: 10000,  reachLabel: "LR4",      fiberType: "SMF", connector: "LC",   wavelengths: "1295-1310nm", standard: "100GBASE-LR4" },

  // ── SONET / SDH optics (SBC TDM gateway, SONUS heritage) ─────────────────
  { pid: "SFP-OC3-SR",       formFactor: "SFP",   speedGbps: 0.155, speed: "OC-3",  reachMeters: 2000,   reachLabel: "OC3-SR",   fiberType: "MMF", connector: "LC",   wavelengths: "1310nm",      standard: "OC-3/STM-1",  notes: "SONET OC-3 155Mbps SR for Ribbon SBC TDM gateway", isTelecom: true },
  { pid: "SFP-OC3-LR",       formFactor: "SFP",   speedGbps: 0.155, speed: "OC-3",  reachMeters: 15000,  reachLabel: "OC3-LR",   fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",      standard: "OC-3/STM-1",  notes: "SONET OC-3 155Mbps LR for inter-CO SBC TDM gateway", isTelecom: true },
  { pid: "SFP-OC12-SR",      formFactor: "SFP",   speedGbps: 0.622, speed: "OC-12", reachMeters: 2000,   reachLabel: "OC12-SR",  fiberType: "MMF", connector: "LC",   wavelengths: "1310nm",      standard: "OC-12/STM-4", notes: "SONET OC-12 622Mbps SR for SONUS GSX SBC trunk", isTelecom: true },
  { pid: "SFP-OC12-LR",      formFactor: "SFP",   speedGbps: 0.622, speed: "OC-12", reachMeters: 40000,  reachLabel: "OC12-LR",  fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",      standard: "OC-12/STM-4", notes: "SONET OC-12 622Mbps LR for long-haul SBC OC-12 trunks", isTelecom: true },
  { pid: "SFP-OC48-SR",      formFactor: "SFP",   speedGbps: 2.5,   speed: "OC-48", reachMeters: 2000,   reachLabel: "OC48-SR",  fiberType: "MMF", connector: "LC",   wavelengths: "1310nm",      standard: "OC-48/STM-16",notes: "SONET OC-48 2.5Gbps SR for Ribbon SBC high-density SONET trunk", isTelecom: true },

  // ── DWDM / Coherent (Apollo IP/Optical) ─────────────────────────────────
  { pid: "DWDM-SFP-C",       formFactor: "SFP+",  speedGbps: 10,  speed: "10G",   reachMeters: 80000,  reachLabel: "DWDM",     fiberType: "SMF", connector: "LC",   wavelengths: "C-band",      notes: "10G DWDM SFP+ fixed-wavelength C-band for Apollo 9400 line card", isTelecom: true },
  { pid: "CFP2-100G-LR4",    formFactor: "CFP2",  speedGbps: 100, speed: "100G",  reachMeters: 10000,  reachLabel: "LR4",      fiberType: "SMF", connector: "LC",   wavelengths: "1295-1310nm", standard: "100GBASE-LR4", notes: "CFP2 100G LR4 for Apollo 9500 coherent line ports", isTelecom: true },
];

export async function scrapeRibbonCommsOem(): Promise<void> {
  console.log("=== Ribbon Communications (ribbon-comms) OEM Transceiver Seed ===\n");

  const vendorId = await ensureVendor(
    "Ribbon Communications",
    "oem",
    "https://ribboncommunications.com",
    undefined
  );

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

  for (const p of RIBBON_COMMS_PIDS) {
    const slug = `ribbon-comms-${p.pid.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
    const category = p.isTelecom ? "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),
           is_oem_seed  = true,
           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=== Ribbon Communications OEM Seed Complete ===`);
  console.log(`  Inserted: ${inserted}`);
  console.log(`  Updated:  ${updated}`);
  console.log(`  Errors:   ${errors}`);
  console.log(`  Total PIDs: ${RIBBON_COMMS_PIDS.length}\n`);
}

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