/**
 * Moxa OEM Transceiver Catalog Seed
 *
 * Seeds transceiver PIDs for Moxa industrial-grade SFP modules used in
 * EDS, PT, and ICS series industrial Ethernet managed switches.
 *
 * Sources:
 *  - Moxa SFP/SFP+ module datasheet (moxa.com)
 *  - Moxa EDS-G series hardware installation guides
 *
 * Run:  tsx packages/scraper/src/scrapers/moxa-oem.ts
 * Cron: daily at 11:15
 */

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

interface MoxaPID {
  pid: string;
  formFactor: string;
  speedGbps: number;
  speed: string;
  reachMeters: number;
  reachLabel: string;
  fiberType: string;
  connector: string;
  wavelengths?: string;
  standard?: string;
  notes?: string;
}

const MOXA_PIDS: MoxaPID[] = [
  // ── 1G SFP (industrial grade) ───────────────────────────────────────────
  { pid: "SFP-1GSXLC",   formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 550,   reachLabel: "SX",   fiberType: "MMF", connector: "LC",   wavelengths: "850nm",  standard: "1000BASE-SX", notes: "Moxa industrial 1G SX" },
  { pid: "SFP-1GLXLC",   formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 10000, reachLabel: "LX",   fiberType: "SMF", connector: "LC",   wavelengths: "1310nm", standard: "1000BASE-LX", notes: "Moxa industrial 1G LX" },
  { pid: "SFP-1GLHLC",   formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 40000, reachLabel: "LH40", fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",                          notes: "Moxa industrial 1G 40km" },
  { pid: "SFP-1GZXLC",   formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 80000, reachLabel: "ZX",   fiberType: "SMF", connector: "LC",   wavelengths: "1550nm", standard: "1000BASE-ZX", notes: "Moxa industrial 1G ZX" },
  { pid: "SFP-1G-T",     formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 100,   reachLabel: "T",    fiberType: "DAC", connector: "RJ45",                        standard: "1000BASE-T",  notes: "Moxa 1G copper SFP" },
  { pid: "SFP-1GSXLC-T", formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 550,   reachLabel: "SX",   fiberType: "MMF", connector: "LC",   wavelengths: "850nm",                           notes: "Moxa 1G SX IND temp -40~85°C" },
  { pid: "SFP-1GLXLC-T", formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 10000, reachLabel: "LX",   fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",                          notes: "Moxa 1G LX IND temp -40~85°C" },
  { pid: "SFP-1GZXLC-T", formFactor: "SFP",   speedGbps: 1,   speed: "1G",   reachMeters: 80000, reachLabel: "ZX",   fiberType: "SMF", connector: "LC",   wavelengths: "1550nm",                          notes: "Moxa 1G ZX IND temp -40~85°C" },

  // ── 10G SFP+ ────────────────────────────────────────────────────────────
  { pid: "SFP-10GSRLC",   formFactor: "SFP+",  speedGbps: 10,  speed: "10G",  reachMeters: 300,   reachLabel: "SR",   fiberType: "MMF", connector: "LC",   wavelengths: "850nm",  standard: "10GBASE-SR",  notes: "Moxa industrial 10G SR" },
  { pid: "SFP-10GLRLC",   formFactor: "SFP+",  speedGbps: 10,  speed: "10G",  reachMeters: 10000, reachLabel: "LR",   fiberType: "SMF", connector: "LC",   wavelengths: "1310nm", standard: "10GBASE-LR",  notes: "Moxa industrial 10G LR" },
  { pid: "SFP-10GERLC",   formFactor: "SFP+",  speedGbps: 10,  speed: "10G",  reachMeters: 40000, reachLabel: "ER",   fiberType: "SMF", connector: "LC",   wavelengths: "1550nm", standard: "10GBASE-ER" },
  { pid: "SFP-10GZRLC",   formFactor: "SFP+",  speedGbps: 10,  speed: "10G",  reachMeters: 80000, reachLabel: "ZR",   fiberType: "SMF", connector: "LC",   wavelengths: "1550nm", standard: "10GBASE-ZR" },
  { pid: "SFP-10GSRLC-T", formFactor: "SFP+",  speedGbps: 10,  speed: "10G",  reachMeters: 300,   reachLabel: "SR",   fiberType: "MMF", connector: "LC",   wavelengths: "850nm",                           notes: "Moxa 10G SR IND temp" },
  { pid: "SFP-10GLRLC-T", formFactor: "SFP+",  speedGbps: 10,  speed: "10G",  reachMeters: 10000, reachLabel: "LR",   fiberType: "SMF", connector: "LC",   wavelengths: "1310nm",                          notes: "Moxa 10G LR IND temp" },

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

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

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

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

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

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