/**
 * Comtrend OEM Transceiver Catalog Seed
 *
 * Seeds Comtrend-branded transceiver PIDs for DSL/GPON/XGS-PON/EPON
 * CPE and OLT access platforms.
 * Comtrend is a DSL and fibre access networking vendor supplying SFP
 * modules for GPON, XGS-PON, EPON, and GE/10GE CPE and OLT equipment.
 *
 * Sources:
 *  - Comtrend GPON OLT/ONU SFP Module Data Sheets
 *  - Comtrend XGS-PON Pluggable Optics Guide
 *  - Comtrend EPON SFP Specification Documents
 *  - comtrend.com product catalogue
 *
 * Run:  tsx packages/scraper/src/scrapers/comtrend-oem.ts
 * Cron: daily at 01:30
 */

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

interface ComtrendPID {
  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 COMTREND_PIDS: ComtrendPID[] = [
  // ── Standard 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: "T",          fiberType: "Cu",  connector: "RJ45", standard: "1000BASE-T" },

  // ── 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", notes: "Comtrend 10G ZR for extended backhaul" },

  // ── GPON SFP (OLT-side, 1490nm TX / 1310nm RX) ───────────────────────────
  { pid: "SFP-GPON-OLT",         formFactor: "SFP",   speedGbps: 1.244, speed: "GPON",  reachMeters: 20000, reachLabel: "OLT",      fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm", standard: "ITU-T G.984", category: "Telecom", notes: "Comtrend GPON OLT SFP — 1490nm TX, 1310nm RX, class B+" },
  // ── GPON SFP (ONU-side, 1310nm TX / 1490nm RX) ───────────────────────────
  { pid: "SFP-GPON-ONU",         formFactor: "SFP",   speedGbps: 1.244, speed: "GPON",  reachMeters: 20000, reachLabel: "ONU",      fiberType: "SMF", connector: "SC",  wavelengths: "1310/1490nm", standard: "ITU-T G.984", category: "Telecom", notes: "Comtrend GPON ONU SFP — 1310nm TX, 1490nm RX" },

  // ── XGS-PON SFP+ (OLT-side) ──────────────────────────────────────────────
  { pid: "SFP-XGS-PON-OLT",      formFactor: "SFP+",  speedGbps: 10,  speed: "XGS-PON", reachMeters: 20000, reachLabel: "OLT",     fiberType: "SMF", connector: "SC",  wavelengths: "1577/1270nm", standard: "ITU-T G.9807.1", category: "Telecom", notes: "Comtrend XGS-PON OLT SFP+ — 1577nm TX, 1270nm RX" },
  // ── XGS-PON SFP+ (ONU-side) ──────────────────────────────────────────────
  { pid: "SFP-XGS-PON-ONU",      formFactor: "SFP+",  speedGbps: 10,  speed: "XGS-PON", reachMeters: 20000, reachLabel: "ONU",     fiberType: "SMF", connector: "SC",  wavelengths: "1270/1577nm", standard: "ITU-T G.9807.1", category: "Telecom", notes: "Comtrend XGS-PON ONU SFP+ — 1270nm TX, 1577nm RX" },

  // ── EPON SFP (OLT-side) ──────────────────────────────────────────────────
  { pid: "SFP-EPON-OLT",         formFactor: "SFP",   speedGbps: 1.25, speed: "EPON",  reachMeters: 20000, reachLabel: "OLT",      fiberType: "SMF", connector: "SC",  wavelengths: "1490/1310nm", standard: "IEEE 802.3ah", category: "Telecom", notes: "Comtrend EPON OLT SFP — 1490nm TX, 1310nm RX" },
  // ── EPON SFP (ONU-side) ──────────────────────────────────────────────────
  { pid: "SFP-EPON-ONU",         formFactor: "SFP",   speedGbps: 1.25, speed: "EPON",  reachMeters: 20000, reachLabel: "ONU",      fiberType: "SMF", connector: "SC",  wavelengths: "1310/1490nm", standard: "IEEE 802.3ah", category: "Telecom", notes: "Comtrend EPON ONU SFP — 1310nm TX, 1490nm RX" },

  // ── BiDi SFP ─────────────────────────────────────────────────────────────
  { pid: "SFP-BIDI-1310-1490",   formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 20000,  reachLabel: "BiDi",       fiberType: "SMF", connector: "LC",  wavelengths: "1310/1490nm", category: "Telecom", notes: "Comtrend BiDi SFP 1310nm TX / 1490nm RX" },
  { pid: "SFP-BIDI-1310-1550",   formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 40000,  reachLabel: "BiDi",       fiberType: "SMF", connector: "LC",  wavelengths: "1310/1550nm", category: "Telecom", notes: "Comtrend BiDi SFP 1310nm TX / 1550nm RX" },
  { pid: "SFP-GE-BIDI-1550",     formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 40000,  reachLabel: "BiDi-1550",  fiberType: "SMF", connector: "LC",  wavelengths: "1550/1310nm", category: "Telecom", notes: "Comtrend BiDi SFP 1550nm TX / 1310nm RX" },

  // ── 10G BiDi SFP+ ────────────────────────────────────────────────────────
  { pid: "SFP-10G-BIDI-1270",    formFactor: "SFP+",  speedGbps: 10,  speed: "10G",  reachMeters: 10000,  reachLabel: "BiDi",       fiberType: "SMF", connector: "LC",  wavelengths: "1270/1330nm", category: "Telecom", notes: "Comtrend 10G BiDi SFP+ 1270nm TX / 1330nm RX" },

  // ── 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" },
];

// PIDs that use 'Telecom' category (PON, BiDi, ZR)
const TELECOM_PIDS = new Set([
  "SFP-10G-ZR",
  "SFP-GPON-OLT",
  "SFP-GPON-ONU",
  "SFP-XGS-PON-OLT",
  "SFP-XGS-PON-ONU",
  "SFP-EPON-OLT",
  "SFP-EPON-ONU",
  "SFP-BIDI-1310-1490",
  "SFP-BIDI-1310-1550",
  "SFP-GE-BIDI-1550",
  "SFP-10G-BIDI-1270",
]);

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

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

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

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

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