/**
 * Datang Telecom / CICT OEM Transceiver Catalog Seed
 *
 * Seeds Datang-branded transceiver PIDs used in TD-LTE and 5G NR base stations,
 * OTN/DWDM transport systems, and carrier Ethernet platforms from Datang Telecom
 * Technology (大唐电信) and its subsidiary CICT Mobile Communication Technology.
 * Includes telecom-grade OTN, CWDM, DWDM, and CFP form factors in addition to
 * standard DataCenter SFP/QSFP variants.
 *
 * Sources:
 *  - CICT Mobile Product Catalog (cictmobile.com)
 *  - Datang Telecom TD-LTE/NR hardware guides
 *  - OTN/DWDM transceiver specification sheets
 *  - SFF-8024 and ITU-T G.698.2 DWDM channel plans
 *
 * Run:  tsx packages/scraper/src/scrapers/datang-oem.ts
 * Cron: daily at 04:00
 */

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

interface DatangPID {
  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 DATANG_PIDS: DatangPID[] = [
  // ── 1G SFP (DataCenter) ─────────────────────────────────────────────────
  { pid: "SFP-1G-SX",          formFactor: "SFP",    speedGbps: 1,   speed: "1G",   reachMeters: 550,    reachLabel: "SX",     fiberType: "MMF", connector: "LC",   wavelengths: "850nm",          standard: "1000BASE-SX",    notes: "Datang 1G SFP SX for TD-LTE eNodeB uplink" },
  { 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-GE-T",           formFactor: "SFP",    speedGbps: 1,   speed: "1G",   reachMeters: 100,    reachLabel: "T",      fiberType: "DAC", connector: "RJ45",                                standard: "1000BASE-T",     notes: "Copper GE SFP for management/S1 interface" },

  // ── 10G SFP+ (DataCenter) ───────────────────────────────────────────────
  { pid: "SFP-10G-SR",         formFactor: "SFP+",   speedGbps: 10,  speed: "10G",  reachMeters: 300,    reachLabel: "SR",     fiberType: "MMF", connector: "LC",   wavelengths: "850nm",          standard: "10GBASE-SR",     notes: "Datang 10G SFP+ SR for 5G NR gNB fronthaul" },
  { 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" },

  // ── 10G ZR SFP+ (Telecom — long-haul OTN backhaul) ─────────────────────
  { 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", notes: "Datang 10G ZR for OTN ring backhaul; carrier transport" },

  // ── SDH / SONET OC-3 / OC-12 SFP (Telecom) ─────────────────────────────
  { pid: "SFP-OC3-SR",         formFactor: "SFP",    speedGbps: 0.155, speed: "155M", reachMeters: 2000, reachLabel: "SR",     fiberType: "MMF", connector: "LC",   wavelengths: "1310nm",         standard: "OC-3/STM-1",     category: "Telecom", notes: "Datang OC-3/STM-1 SFP for SDH legacy circuit interconnect" },
  { pid: "SFP-OC12-SR",        formFactor: "SFP",    speedGbps: 0.622, speed: "622M", reachMeters: 2000, reachLabel: "SR",     fiberType: "MMF", connector: "LC",   wavelengths: "1310nm",         standard: "OC-12/STM-4",    category: "Telecom", notes: "Datang OC-12/STM-4 SFP; TD-LTE legacy SDH transport" },

  // ── OTU2 10G SFP+ (Telecom) ─────────────────────────────────────────────
  { pid: "SFP-OTU2-10G",       formFactor: "SFP+",   speedGbps: 10,  speed: "10G",  reachMeters: 40000,  reachLabel: "ER",     fiberType: "SMF", connector: "LC",   wavelengths: "1550nm",         standard: "G.709 OTU2",     category: "Telecom", notes: "Datang OTU2 10G SFP+ for OTN framing on backhaul links" },

  // ── 25G SFP28 (DataCenter) ──────────────────────────────────────────────
  { pid: "SFP28-25G-LR",       formFactor: "SFP28",  speedGbps: 25,  speed: "25G",  reachMeters: 10000,  reachLabel: "LR",     fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",         standard: "25GBASE-LR",     notes: "Datang 25G SFP28 for 5G NR C-RAN fronthaul (eCPRI)" },

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

  // ── 100G QSFP28 (DataCenter) ────────────────────────────────────────────
  { pid: "QSFP28-100G-LR4",    formFactor: "QSFP28", speedGbps: 100, speed: "100G", reachMeters: 10000,  reachLabel: "LR4",    fiberType: "SMF", connector: "LC",   wavelengths: "1295-1310nm",    standard: "100GBASE-LR4",   notes: "Datang 100G QSFP28 LR4 for 5G midhaul aggregation" },

  // ── CWDM SFP (Telecom) ──────────────────────────────────────────────────
  { pid: "SFP-CWDM-1550",      formFactor: "SFP",    speedGbps: 1,   speed: "1G",   reachMeters: 80000,  reachLabel: "CWDM",   fiberType: "SMF", connector: "LC",   wavelengths: "1550nm",         standard: "G.694.2 CWDM",   category: "Telecom", notes: "Datang CWDM SFP 1550nm for metro WDM rings; TD-LTE backhaul" },

  // ── DWDM SFP (Telecom) ──────────────────────────────────────────────────
  { pid: "DWDM-SFP-C",         formFactor: "SFP",    speedGbps: 1,   speed: "1G",   reachMeters: 80000,  reachLabel: "DWDM",   fiberType: "SMF", connector: "LC",   wavelengths: "C-band ITU",     standard: "G.694.1 DWDM",   category: "Telecom", notes: "Datang DWDM SFP C-band (ITU grid) for dense WDM transport" },

  // ── CFP 100G (Telecom — OTN/coherent line-side) ─────────────────────────
  { pid: "CFP-100G-LR4",       formFactor: "CFP",    speedGbps: 100, speed: "100G", reachMeters: 10000,  reachLabel: "LR4",    fiberType: "SMF", connector: "LC",   wavelengths: "1295-1310nm",    standard: "OIF CFP",        category: "Telecom", notes: "Datang 100G CFP LR4 for OTN/SDN line card; carrier transport" },

  // ── 400G QSFP-DD (DataCenter) ───────────────────────────────────────────
  { pid: "QSFP-DD-400G-DR4",   formFactor: "QSFP-DD",speedGbps: 400, speed: "400G", reachMeters: 500,    reachLabel: "DR4",    fiberType: "SMF", connector: "MPO", wavelengths: "1310nm",          standard: "400GBASE-DR4",   notes: "Datang 400G QSFP-DD for 5G core DC interconnect" },
];

// PIDs classified as Telecom (OTN, SONET/SDH, CWDM, DWDM, coherent CFP, ZR)
const TELECOM_PIDS = new Set([
  "SFP-10G-ZR",
  "SFP-OC3-SR",
  "SFP-OC12-SR",
  "SFP-OTU2-10G",
  "SFP-CWDM-1550",
  "DWDM-SFP-C",
  "CFP-100G-LR4",
]);

export async function scrapeDatangOem(): Promise<void> {
  console.log("=== Datang Telecom / CICT OEM Transceiver Seed ===\n");

  const vendorId = await ensureVendor(
    "Datang Telecom",
    "oem",
    "https://www.cictmobile.com",
    undefined
  );

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

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

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