/**
 * Teleste OEM Transceiver Catalog Seed
 *
 * Seeds Teleste-branded transceiver PIDs for CATV/HFC hybrid-fibre-coax
 * infrastructure, broadband access, and optical transport platforms.
 * Teleste is a Finnish vendor specialising in cable TV and broadband networks.
 *
 * Sources:
 *  - Teleste Optical Products Portfolio (teleste.com)
 *  - Teleste HFC Network Optics Datasheet
 *  - Teleste CWDM/BiDi Access Module Guide
 *
 * Run:  tsx packages/scraper/src/scrapers/teleste-oem.ts
 * Cron: daily at 23:45
 */

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

interface TelestePID {
  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 TELESTE_PIDS: TelestePID[] = [
  // ── 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-GE-T",             formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 100,    reachLabel: "RJ45", 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" },

  // ── BiDi SFP ─────────────────────────────────────────────────────────────
  { pid: "SFP-BIDI-1310-1550",   formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 20000,  reachLabel: "BIDI", fiberType: "SMF", connector: "LC",  wavelengths: "1310/1550nm", category: "Telecom", notes: "Teleste 1G BiDi SFP 1310Tx/1550Rx for HFC upstream/downstream" },

  // ── 1G CWDM SFP (HFC access wavelengths) ─────────────────────────────────
  { pid: "SFP-CWDM-1470",        formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 40000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1470nm",      category: "Telecom", notes: "Teleste CWDM SFP 1470nm for HFC overlay" },
  { pid: "SFP-CWDM-1490",        formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 40000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1490nm",      category: "Telecom", notes: "Teleste CWDM SFP 1490nm for HFC overlay" },
  { pid: "SFP-CWDM-1510",        formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 40000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1510nm",      category: "Telecom", notes: "Teleste CWDM SFP 1510nm for HFC overlay" },
  { pid: "SFP-CWDM-1530",        formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 40000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1530nm",      category: "Telecom", notes: "Teleste CWDM SFP 1530nm for HFC overlay" },
  { pid: "SFP-CWDM-1550",        formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 60000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1550nm",      category: "Telecom", notes: "Teleste CWDM SFP 1550nm for HFC overlay" },
  { pid: "SFP-CWDM-1570",        formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 40000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1570nm",      category: "Telecom", notes: "Teleste CWDM SFP 1570nm for HFC overlay" },
  { pid: "SFP-CWDM-1590",        formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 40000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1590nm",      category: "Telecom", notes: "Teleste CWDM SFP 1590nm for HFC overlay" },
  { pid: "SFP-CWDM-1610",        formFactor: "SFP",     speedGbps: 1,   speed: "1G",   reachMeters: 40000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1610nm",      category: "Telecom", notes: "Teleste CWDM SFP 1610nm for HFC overlay" },

  // ── CATV Analogue Optical ─────────────────────────────────────────────────
  { pid: "SFP-CATV-1550",        formFactor: "SFP",     speedGbps: 1,   speed: "CATV", reachMeters: 30000,  reachLabel: "CATV", fiberType: "SMF", connector: "SC",  wavelengths: "1550nm",      category: "Telecom", notes: "Teleste CATV analogue optical SFP 1550nm for HFC RF overlay" },

  // ── 10G CWDM SFP+ ────────────────────────────────────────────────────────
  { pid: "SFP-10G-CWDM-1470",    formFactor: "SFP+",    speedGbps: 10,  speed: "10G",  reachMeters: 40000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1470nm",      category: "Telecom", notes: "Teleste 10G CWDM SFP+ 1470nm" },
  { pid: "SFP-10G-CWDM-1550",    formFactor: "SFP+",    speedGbps: 10,  speed: "10G",  reachMeters: 60000,  reachLabel: "CWDM", fiberType: "SMF", connector: "LC",  wavelengths: "1550nm",      category: "Telecom", notes: "Teleste 10G CWDM SFP+ 1550nm" },
];

// PIDs that use 'Telecom' category (CWDM, CATV analogue, BiDi HFC)
const TELECOM_PIDS = new Set([
  "SFP-BIDI-1310-1550",
  "SFP-CWDM-1470",
  "SFP-CWDM-1490",
  "SFP-CWDM-1510",
  "SFP-CWDM-1530",
  "SFP-CWDM-1550",
  "SFP-CWDM-1570",
  "SFP-CWDM-1590",
  "SFP-CWDM-1610",
  "SFP-CATV-1550",
  "SFP-10G-CWDM-1470",
  "SFP-10G-CWDM-1550",
]);

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

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

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

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

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