/**
 * Huawei Access OEM Transceiver Catalog Seed
 *
 * Seeds Huawei Access-branded transceiver PIDs for SmartAX OLT platforms
 * (MA5800, MA5600T) supporting GPON, XGS-PON, and 25G-PON line cards.
 *
 * Sources:
 *  - Huawei Fixed Network Access OLT Product Page (carrier.huawei.com)
 *  - Huawei SmartAX MA5800 Hardware Description
 *  - Huawei XGS-PON / 25G-PON Optical Module Data Sheets
 *
 * Run:  tsx packages/scraper/src/scrapers/huawei-access-oem.ts
 * Cron: daily at 08:30
 */

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

interface HuaweiAccessPID {
  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([
  "H3C-GPON-OLT-CLASS-B",
  "H3C-GPON-OLT-CLASS-C",
  "HW-XGSPON-OLT-1577",
  "HW-XGSPON-ONU-1270",
  "HW-EPON-OLT",
  "HW-10G-EPON-OLT",
  "HW-25G-PON-OLT",
  "HW-SFP-CWDM-1490",
  "HW-SFP-CWDM-1550",
  "HW-SFP-BIDI-1310",
  "HW-SFP-BIDI-1490",
  "HW-SFP-10G-BIDI-1270",
]);

const HUAWEI_ACCESS_PIDS: HuaweiAccessPID[] = [
  // ── GPON OLT SFP ─────────────────────────────────────────────────────────
  { pid: "H3C-GPON-OLT-CLASS-B",  formFactor: "SFP",    speedGbps: 2.488, speed: "GPON",      reachMeters: 20000, reachLabel: "GPON-20K",    fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm", standard: "G.984",    notes: "Huawei Access GPON OLT SFP Class B+, SmartAX platform",  isTelecom: true },
  { pid: "H3C-GPON-OLT-CLASS-C",  formFactor: "SFP",    speedGbps: 2.488, speed: "GPON",      reachMeters: 20000, reachLabel: "GPON-C+",     fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm", standard: "G.984",    notes: "Huawei Access GPON OLT SFP Class C+, extended reach",     isTelecom: true },

  // ── XGS-PON OLT / ONU SFP+ ───────────────────────────────────────────────
  { pid: "HW-XGSPON-OLT-1577",    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: "Huawei Access XGS-PON OLT SFP+ for MA5800",               isTelecom: true },
  { pid: "HW-XGSPON-ONU-1270",     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: "Huawei Access XGS-PON ONU SFP+ 1270nm TX",                isTelecom: true },

  // ── EPON OLT SFP ─────────────────────────────────────────────────────────
  { pid: "HW-EPON-OLT",            formFactor: "SFP",    speedGbps: 1,     speed: "EPON",      reachMeters: 20000, reachLabel: "EPON-20K",    fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm", standard: "802.3ah",  notes: "Huawei Access EPON OLT SFP 1G/1G",                        isTelecom: true },
  { pid: "HW-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: "Huawei Access 10G-EPON OLT SFP+",                         isTelecom: true },

  // ── 25G-PON OLT SFP28 ────────────────────────────────────────────────────
  { pid: "HW-25G-PON-OLT",         formFactor: "SFP28",  speedGbps: 25,    speed: "25G-PON",   reachMeters: 20000, reachLabel: "25G-PON-20K", fiberType: "SMF", connector: "SC",  wavelengths: "1577/1270nm", standard: "G.9804.3", notes: "Huawei Access 25G-PON OLT SFP28",                          isTelecom: true },

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

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

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

  // ── BiDi SFP ─────────────────────────────────────────────────────────────
  { pid: "HW-SFP-BIDI-1310",       formFactor: "SFP",    speedGbps: 1,     speed: "1G",        reachMeters: 20000, reachLabel: "BiDi-1310",   fiberType: "SMF", connector: "SC",  wavelengths: "1310/1490nm",                         notes: "Huawei Access 1G BiDi SFP 1310nm TX / 1490nm RX",        isTelecom: true },
  { pid: "HW-SFP-BIDI-1490",       formFactor: "SFP",    speedGbps: 1,     speed: "1G",        reachMeters: 20000, reachLabel: "BiDi-1490",   fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm",                         notes: "Huawei Access 1G BiDi SFP 1490nm TX / 1310nm RX",        isTelecom: true },
  { pid: "HW-SFP-10G-BIDI-1270",   formFactor: "SFP+",   speedGbps: 10,    speed: "10G",       reachMeters: 20000, reachLabel: "BiDi-1270",   fiberType: "SMF", connector: "LC",  wavelengths: "1270/1330nm",                         notes: "Huawei Access 10G BiDi SFP+ 1270nm TX",                  isTelecom: true },

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

  // ── 40G / 100G QSFP ──────────────────────────────────────────────────────
  { pid: "HW-QSFP-40G-LR4",        formFactor: "QSFP+",  speedGbps: 40,    speed: "40G",       reachMeters: 10000, reachLabel: "LR4",         fiberType: "SMF", connector: "LC",  wavelengths: "1310nm",      standard: "40GBASE-LR4" },
  { pid: "HW-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 scrapeHuaweiAccessOem(): Promise<void> {
  console.log("=== Huawei Access OEM Transceiver Seed ===\n");

  const vendorId = await ensureVendor(
    "Huawei Access",
    "oem",
    "https://carrier.huawei.com/en/products/fixed-network/access/olt",
    undefined
  );

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

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

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