/**
 * Calix GigaPoint OEM Transceiver Catalog Seed
 *
 * Seeds Calix GigaPoint / Revenue EDGE-branded transceiver PIDs for
 * Calix E-Series and AXOS OLT platforms supporting GPON, XGS-PON,
 * and 10G-EPON broadband access deployments.
 *
 * Sources:
 *  - Calix Broadband Cloud Access Systems (calix.com)
 *  - Calix E7-2 / AXOS E9-2 Hardware Reference Guides
 *  - Calix GigaPoint Optical Module Data Sheets
 *
 * Run:  tsx packages/scraper/src/scrapers/calix-gigapoint-oem.ts
 * Cron: daily at 09:00
 */

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

interface CalixGigapointPID {
  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 TELECOM_PIDS: Set<string> = new Set([
  "CGP-GPON-OLT-B",
  "CGP-GPON-OLT-C",
  "CGP-XGS-PON-OLT",
  "CGP-XGS-PON-ONU",
  "CGP-EPON-OLT",
  "CGP-10G-EPON-OLT",
  "CGP-SFP-CWDM-1490",
  "CGP-SFP-CWDM-1550",
  "CGP-SFP-BIDI-1310",
  "CGP-SFP-BIDI-1490",
]);

const CALIX_GIGAPOINT_PIDS: CalixGigapointPID[] = [
  // ── GPON OLT SFP ─────────────────────────────────────────────────────────
  { pid: "CGP-GPON-OLT-B",    formFactor: "SFP",    speedGbps: 2.488, speed: "GPON",      reachMeters: 20000, reachLabel: "GPON-20K",    fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm", standard: "G.984",    notes: "Calix GigaPoint GPON OLT SFP Class B+, E7-2/AXOS platform", isTelecom: true },
  { pid: "CGP-GPON-OLT-C",    formFactor: "SFP",    speedGbps: 2.488, speed: "GPON",      reachMeters: 20000, reachLabel: "GPON-C+",     fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm", standard: "G.984",    notes: "Calix GigaPoint GPON OLT SFP Class C+, extended reach",      isTelecom: true },

  // ── XGS-PON OLT / ONU SFP+ ───────────────────────────────────────────────
  { pid: "CGP-XGS-PON-OLT",   formFactor: "SFP+",   speedGbps: 10,    speed: "XGS-PON",   reachMeters: 20000, reachLabel: "XGS-PON-20K", fiberType: "SMF", connector: "SC",  wavelengths: "1577/1270nm", standard: "G.9807.1", notes: "Calix GigaPoint XGS-PON OLT SFP+ for E9-2",                  isTelecom: true },
  { pid: "CGP-XGS-PON-ONU",   formFactor: "SFP+",   speedGbps: 10,    speed: "XGS-PON",   reachMeters: 20000, reachLabel: "XGS-ONU-20K", fiberType: "SMF", connector: "SC",  wavelengths: "1270/1577nm", standard: "G.9807.1", notes: "Calix GigaPoint XGS-PON ONU SFP+ 1270nm TX",                 isTelecom: true },

  // ── EPON OLT SFP ─────────────────────────────────────────────────────────
  { pid: "CGP-EPON-OLT",       formFactor: "SFP",    speedGbps: 1,     speed: "EPON",      reachMeters: 20000, reachLabel: "EPON-20K",    fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm", standard: "802.3ah",  notes: "Calix GigaPoint EPON OLT SFP 1G/1G",                         isTelecom: true },
  { pid: "CGP-10G-EPON-OLT",   formFactor: "SFP+",   speedGbps: 10,    speed: "10G-EPON",  reachMeters: 20000, reachLabel: "10G-EPON-20K",fiberType: "SMF", connector: "SC",  wavelengths: "1577/1270nm", standard: "802.3av",  notes: "Calix GigaPoint 10G-EPON OLT SFP+",                          isTelecom: true },

  // ── Standard 1G SFP ──────────────────────────────────────────────────────
  { pid: "CGP-SFP-1G-SX",      formFactor: "SFP",    speedGbps: 1,     speed: "1G",        reachMeters: 550,   reachLabel: "SX",          fiberType: "MMF", connector: "LC",  wavelengths: "850nm",       standard: "1000BASE-SX" },
  { pid: "CGP-SFP-1G-LX",      formFactor: "SFP",    speedGbps: 1,     speed: "1G",        reachMeters: 10000, reachLabel: "LX",          fiberType: "SMF", connector: "LC",  wavelengths: "1310nm",      standard: "1000BASE-LX" },

  // ── Standard 10G SFP+ ────────────────────────────────────────────────────
  { pid: "CGP-SFP-10G-SR",     formFactor: "SFP+",   speedGbps: 10,    speed: "10G",       reachMeters: 300,   reachLabel: "SR",          fiberType: "MMF", connector: "LC",  wavelengths: "850nm",       standard: "10GBASE-SR" },
  { pid: "CGP-SFP-10G-LR",     formFactor: "SFP+",   speedGbps: 10,    speed: "10G",       reachMeters: 10000, reachLabel: "LR",          fiberType: "SMF", connector: "LC",  wavelengths: "1310nm",      standard: "10GBASE-LR" },

  // ── CWDM SFP ─────────────────────────────────────────────────────────────
  { pid: "CGP-SFP-CWDM-1490",  formFactor: "SFP",    speedGbps: 1,     speed: "1G",        reachMeters: 40000, reachLabel: "CWDM-1490",   fiberType: "SMF", connector: "LC",  wavelengths: "1490nm",      standard: "CWDM",     notes: "Calix GigaPoint CWDM SFP 1490nm",                            isTelecom: true },
  { pid: "CGP-SFP-CWDM-1550",  formFactor: "SFP",    speedGbps: 1,     speed: "1G",        reachMeters: 40000, reachLabel: "CWDM-1550",   fiberType: "SMF", connector: "LC",  wavelengths: "1550nm",      standard: "CWDM",     notes: "Calix GigaPoint CWDM SFP 1550nm",                            isTelecom: true },

  // ── BiDi SFP ─────────────────────────────────────────────────────────────
  { pid: "CGP-SFP-BIDI-1310",  formFactor: "SFP",    speedGbps: 1,     speed: "1G",        reachMeters: 20000, reachLabel: "BiDi-1310",   fiberType: "SMF", connector: "SC",  wavelengths: "1310/1490nm",                         notes: "Calix GigaPoint 1G BiDi SFP 1310nm TX / 1490nm RX",          isTelecom: true },
  { pid: "CGP-SFP-BIDI-1490",  formFactor: "SFP",    speedGbps: 1,     speed: "1G",        reachMeters: 20000, reachLabel: "BiDi-1490",   fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm",                         notes: "Calix GigaPoint 1G BiDi SFP 1490nm TX / 1310nm RX",          isTelecom: true },

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

  // ── 100G QSFP28 ──────────────────────────────────────────────────────────
  { pid: "CGP-QSFP-100G-LR4",  formFactor: "QSFP28", speedGbps: 100,   speed: "100G",      reachMeters: 10000, reachLabel: "LR4",         fiberType: "SMF", connector: "LC",  wavelengths: "1295-1310nm", standard: "100GBASE-LR4" },
];

export async function scrapeCalixGigapointOem(): Promise<void> {
  console.log("=== Calix GigaPoint OEM Transceiver Seed ===\n");

  const vendorId = await ensureVendor(
    "Calix GigaPoint",
    "oem",
    "https://www.calix.com/calix-platforms/calix-broadband-cloud-access-systems.html",
    undefined
  );

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

  for (const p of CALIX_GIGAPOINT_PIDS) {
    const slug = `calix-gp-${p.pid.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
    const 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=== Calix GigaPoint OEM Seed Complete ===`);
  console.log(`  Inserted: ${inserted}`);
  console.log(`  Updated:  ${updated}`);
  console.log(`  Errors:   ${errors}`);
  console.log(`  Total PIDs: ${CALIX_GIGAPOINT_PIDS.length}\n`);
}

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