/**
 * ADTRAN Total Access OEM Transceiver Catalog Seed
 *
 * Seeds ADTRAN-branded transceiver PIDs for Total Access (TA) platforms,
 * OPTI-6100, SDX, and ADTRAN Optical Networking equipment. Covers
 * enterprise access, PON/GPON OLT optics, and CWDM variants used in
 * ADTRAN's broadband and carrier access product lines.
 *
 * Note: adtran-oem.ts covers general ADTRAN networking PIDs.
 * This file focuses on Total Access (TA) platform optics, PON OLT SFPs,
 * BiDi, and CWDM variants specific to ADTRAN's access/aggregation portfolio.
 *
 * Sources:
 *  - ADTRAN Total Access 5000/6000 Series Compatible Optics
 *  - ADTRAN SDX Series Transceiver Compatibility Matrix
 *  - ADTRAN OPTI-6100 XGS Pluggable Optic Guide
 *  - ADTRAN PON OLT SFP+ Specification Sheet (adtran.com/products/optical)
 *
 * Run:  tsx packages/scraper/src/scrapers/adtran-ta-oem.ts
 * Cron: daily at 00:30
 */

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

interface AdtranTaPID {
  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 ADTRAN_TA_PIDS: AdtranTaPID[] = [
  // ── 1G SFP ──────────────────────────────────────────────────────────────
  { pid: "SFP-1G-SX",          formFactor: "SFP",   speedGbps: 1,    speed: "1G",      reachMeters: 550,     reachLabel: "SX",          fiberType: "MMF", connector: "LC",   wavelengths: "850nm",          standard: "1000BASE-SX" },
  { pid: "SFP-1G-LX",          formFactor: "SFP",   speedGbps: 1,    speed: "1G",      reachMeters: 10000,   reachLabel: "LX",          fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",         standard: "1000BASE-LX" },
  { pid: "SFP-1G-T",           formFactor: "SFP",   speedGbps: 1,    speed: "1G",      reachMeters: 100,     reachLabel: "1000BASE-T",  fiberType: "Cu",  connector: "RJ45" },

  // ── 10G SFP+ ────────────────────────────────────────────────────────────
  { 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",   category: "Telecom" },
  { pid: "SFP-GE-T",           formFactor: "SFP",   speedGbps: 1,    speed: "1G",      reachMeters: 100,     reachLabel: "GE-T",        fiberType: "Cu",  connector: "RJ45" },

  // ── PON OLT SFP (ADTRAN OPTI-6100 / Total Access PON) ───────────────────
  { pid: "SFP-GPON-OLT",       formFactor: "SFP",   speedGbps: 2.488, speed: "GPON",   reachMeters: 20000,   reachLabel: "GPON-OLT",    fiberType: "SMF", connector: "SC",   wavelengths: "1490nm TX / 1310nm RX", standard: "ITU-T G.984", category: "Telecom", notes: "ADTRAN Total Access GPON OLT SFP, ITU-T G.984.2 Class B+" },
  { pid: "SFP-XGS-PON-OLT",    formFactor: "SFP+",  speedGbps: 10,    speed: "XGS-PON", reachMeters: 20000,  reachLabel: "XGS-PON-OLT", fiberType: "SMF", connector: "SC",   wavelengths: "1577nm TX / 1270nm RX", standard: "ITU-T G.9807", category: "Telecom", notes: "ADTRAN SDX 10G XGS-PON OLT SFP+, ITU-T G.9807.1 Class N1" },
  { pid: "SFP-EPON-OLT",       formFactor: "SFP",   speedGbps: 1.25,  speed: "EPON",   reachMeters: 20000,   reachLabel: "EPON-OLT",    fiberType: "SMF", connector: "SC",   wavelengths: "1490nm TX / 1310nm RX", standard: "IEEE 802.3ah", category: "Telecom", notes: "ADTRAN EPON OLT SFP for Total Access EPON/E-PON platforms" },

  // ── BiDi SFP ─────────────────────────────────────────────────────────────
  { pid: "SFP-BIDI-1310-1490", formFactor: "SFP",   speedGbps: 1,    speed: "1G",      reachMeters: 20000,   reachLabel: "BiDi-1310/1490", fiberType: "SMF", connector: "LC", wavelengths: "1310nm TX / 1490nm RX", standard: "1000BASE-BX", category: "Telecom", notes: "ADTRAN BiDi SFP 1310TX/1490RX for WDM-PON access networks" },
  { pid: "SFP-BIDI-1310-1550", formFactor: "SFP",   speedGbps: 1,    speed: "1G",      reachMeters: 40000,   reachLabel: "BiDi-1310/1550", fiberType: "SMF", connector: "LC", wavelengths: "1310nm TX / 1550nm RX", standard: "1000BASE-BX", category: "Telecom", notes: "ADTRAN BiDi SFP 1310TX/1550RX for extended reach access links" },

  // ── 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: "1270-1330nm",    standard: "40GBASE-LR4" },

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

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

  // ── CWDM SFP ─────────────────────────────────────────────────────────────
  { pid: "SFP-CWDM-1550",      formFactor: "SFP",    speedGbps: 1,   speed: "1G",     reachMeters: 40000,   reachLabel: "CWDM-1550",   fiberType: "SMF", connector: "LC",   wavelengths: "1550nm",         standard: "1000BASE-CWDM", category: "Telecom", notes: "ADTRAN CWDM SFP 1550nm for WDM aggregation in TA/SDX platforms" },
];

// PIDs that belong to the Telecom category (PON, BiDi, CWDM, ZR)
const TELECOM_PIDS = new Set([
  "SFP-10G-ZR",
  "SFP-GPON-OLT",
  "SFP-XGS-PON-OLT",
  "SFP-EPON-OLT",
  "SFP-BIDI-1310-1490",
  "SFP-BIDI-1310-1550",
  "SFP-CWDM-1550",
]);

export async function scrapeAdtranTaOem(): Promise<void> {
  console.log("=== ADTRAN Total Access OEM Transceiver Seed ===\n");

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

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

  for (const p of ADTRAN_TA_PIDS) {
    const slug     = `adtran-ta-${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=== ADTRAN Total Access OEM Seed Complete ===`);
  console.log(`  Inserted: ${inserted}`);
  console.log(`  Updated:  ${updated}`);
  console.log(`  Errors:   ${errors}`);
  console.log(`  Total PIDs: ${ADTRAN_TA_PIDS.length}\n`);
}

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