/**
 * OpticsBay Scraper — North American compatible transceiver vendor
 *
 * opticsbay.com — WooCommerce store, USD/CAD pricing.
 * Covers SFP/SFP+/QSFP28/QSFP-DD with competitive pricing.
 * Rate limited: 1 req/2sec.
 *
 * OpticsBay offers compatible optics for Cisco, Juniper, Arista, HPE.
 * Transparent pricing, no login required.
 */
import { pool, findOrCreateScrapedTransceiver, ensureVendor, upsertPriceObservation } from "../utils/db";
import { contentHash } from "../utils/hash";

const BASE = "https://www.opticsbay.com";
const HEADERS = {
  "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  "Accept-Language": "en-US,en;q=0.9",
};

const MAX_PAGES = 20;

const CATEGORIES = [
  { path: "/product-category/sfp-transceiver/",         formFactor: "SFP",     speed: "1G",   speedGbps: 1   },
  { path: "/product-category/sfp-plus-transceiver/",    formFactor: "SFP+",    speed: "10G",  speedGbps: 10  },
  { path: "/product-category/sfp28-transceiver/",       formFactor: "SFP28",   speed: "25G",  speedGbps: 25  },
  { path: "/product-category/qsfp-plus-transceiver/",   formFactor: "QSFP+",   speed: "40G",  speedGbps: 40  },
  { path: "/product-category/qsfp28-transceiver/",      formFactor: "QSFP28",  speed: "100G", speedGbps: 100 },
  { path: "/product-category/qsfp-dd-transceiver/",     formFactor: "QSFP-DD", speed: "400G", speedGbps: 400 },
  { path: "/product-category/dac-cable/",               formFactor: "DAC",     speed: "10G",  speedGbps: 10  },
  { path: "/product-category/transceivers/",            formFactor: "SFP+",    speed: "10G",  speedGbps: 10  },
];

interface Product {
  partNumber: string;
  name: string;
  url: string;
  price?: number;
  formFactor: string;
  speed: string;
  speedGbps: number;
  reachLabel?: string;
  reachMeters?: number;
  fiberType?: string;
  wavelength?: string;
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function detectReach(text: string): { label: string; meters: number } | undefined {
  const patterns: [RegExp, string, number][] = [
    [/\b120\s*km\b/i, "120km", 120000],
    [/\b80\s*km\b/i, "80km", 80000],
    [/\b40\s*km\b/i, "40km", 40000],
    [/\b20\s*km\b/i, "20km", 20000],
    [/\b10\s*km\b/i, "10km", 10000],
    [/\b2\s*km\b/i, "2km", 2000],
    [/\b550\s*m\b/i, "550m", 550],
    [/\b300\s*m\b/i, "300m", 300],
    [/\b100\s*m\b/i, "100m", 100],
    [/\bLR4\b/, "10km", 10000], [/\bLR\b/, "10km", 10000],
    [/\bER4?\b/, "40km", 40000], [/\bZR4?\b/, "80km", 80000],
    [/\bSR4?\b/, "300m", 300],  [/\bDR4?\b/, "500m", 500],
    [/\bFR4?\b/, "2km", 2000],
  ];
  for (const [re, label, meters] of patterns) {
    if (re.test(text)) return { label, meters };
  }
  return undefined;
}

function detectFiber(text: string): string {
  if (/single.?mode|smf|[^a-z]lx[^a-z]|[^a-z]lr[^a-z]|[^a-z]er[^a-z]|[^a-z]zr[^a-z]|bidi|cwdm|dwdm/i.test(text)) return "SMF";
  if (/multi.?mode|mmf|[^a-z]sx[^a-z]|[^a-z]sr[^a-z]/i.test(text)) return "MMF";
  if (/copper|dac|twinax|rj.?45|base-t/i.test(text)) return "Copper";
  return "";
}

function detectWavelength(text: string): string {
  const m = text.match(/(\d{3,4})\s*nm/i);
  return m ? m[1] : "";
}

function parseProductList(html: string, cat: typeof CATEGORIES[number]): Product[] {
  const products: Product[] = [];
  const seen = new Set<string>();
  const collapsed = html.replace(/\s+/g, " ");

  // Strategy 1: WooCommerce standard product loop
  for (const m of collapsed.matchAll(/<li[^>]+class="[^"]*product[^"]*"[^>]*>([\s\S]*?)<\/li>/gi)) {
    const card = m[1];
    const urlMatch = card.match(/href="(https?:\/\/(?:www\.)?opticsbay\.com\/[^"?#]+)"/i);
    if (!urlMatch) continue;
    const url = urlMatch[1];
    if (seen.has(url)) continue;
    seen.add(url);

    const nameMatch =
      card.match(/woocommerce-loop-product__title[^>]*>([^<]+)</i) ||
      card.match(/<h[23][^>]*>([^<]{8,})<\/h[23]>/i);
    if (!nameMatch) continue;
    const name = nameMatch[1].trim().replace(/&amp;/g, "&").replace(/&#\d+;/g, "");
    if (name.length < 5) continue;

    const priceMatch = card.match(/\$\s*([\d,]+\.?\d*)/);
    const price = priceMatch ? parseFloat(priceMatch[1].replace(/,/g, "")) : undefined;
    const reach = detectReach(name);

    products.push({
      partNumber: name.split(/\s+(?:compatible|for\s+[A-Z])/i)[0]?.trim().slice(0, 80) || name.slice(0, 60),
      name, url,
      price: price && price > 0 && price < 100000 ? price : undefined,
      formFactor: cat.formFactor, speed: cat.speed, speedGbps: cat.speedGbps,
      reachLabel: reach?.label, reachMeters: reach?.meters,
      fiberType: detectFiber(name), wavelength: detectWavelength(name),
    });
  }

  // Strategy 2: Generic product link scan
  if (products.length === 0) {
    for (const m of collapsed.matchAll(/href="(https?:\/\/(?:www\.)?opticsbay\.com\/(?:product|shop)\/[^"?#]+)"[^>]*>([^<]{8,})</gi)) {
      const url = m[1];
      const name = m[2].trim().replace(/&amp;/g, "&");
      if (seen.has(url) || name.length < 8) continue;
      if (!/transceiver|sfp|qsfp|dac|optic/i.test(name + url)) continue;
      seen.add(url);

      const idx = collapsed.indexOf(url);
      const ctx = collapsed.slice(Math.max(0, idx - 300), idx + 600);
      const priceM = ctx.match(/\$\s*([\d,]+\.?\d*)/);
      const price = priceM ? parseFloat(priceM[1].replace(/,/g, "")) : undefined;
      const reach = detectReach(name);

      products.push({
        partNumber: name.split(/\s+/)[0]?.slice(0, 80) || "",
        name, url,
        price: price && price > 0 && price < 100000 ? price : undefined,
        formFactor: cat.formFactor, speed: cat.speed, speedGbps: cat.speedGbps,
        reachLabel: reach?.label, reachMeters: reach?.meters,
        fiberType: detectFiber(name), wavelength: detectWavelength(name),
      });
    }
  }

  return products;
}

async function fetchPage(url: string): Promise<string> {
  const resp = await fetch(url, { headers: HEADERS, signal: AbortSignal.timeout(30000) });
  if (!resp.ok) throw new Error(`HTTP ${resp.status} for ${url}`);
  return resp.text();
}

export async function scrapeOpticsBay(): Promise<void> {
  console.log("=== OpticsBay Scraper Starting ===\n");

  const vendorId = await ensureVendor(
    "OpticsBay",
    "compatible",
    "https://www.opticsbay.com",
    "https://www.opticsbay.com/product-category/transceivers/",
  );

  let totalProducts = 0;
  let priceUpdates = 0;
  const seenCategories = new Set<string>();

  for (const cat of CATEGORIES) {
    console.log(`\n--- ${cat.formFactor} (${cat.speed}) [${cat.path}] ---`);

    try {
      const html1 = await fetchPage(BASE + cat.path);
      const catProducts = parseProductList(html1, cat);

      if (cat.path.includes("/transceivers/") && seenCategories.size > 3) {
        console.log(`  Skipping generic fallback (${seenCategories.size} categories scraped)`);
        continue;
      }

      if (catProducts.length === 0) {
        console.log("  No products on page 1 — skipping");
        continue;
      }

      seenCategories.add(cat.path);
      console.log(`  Found ${catProducts.length} products on page 1`);

      const allProducts = [...catProducts];

      for (let page = 2; page <= MAX_PAGES; page++) {
        await sleep(2000);
        try {
          const pageUrl = `${BASE}${cat.path}page/${page}/`;
          const html = await fetchPage(pageUrl);
          const pageProds = parseProductList(html, cat);
          if (pageProds.length === 0) break;
          allProducts.push(...pageProds);
          console.log(`  Page ${page}: ${pageProds.length} products`);
        } catch (err) {
          console.warn(`  Page ${page} failed: ${(err as Error).message.slice(0, 60)}`);
          break;
        }
      }

      const uniqueProducts = allProducts.filter((p, i, arr) => arr.findIndex(x => x.url === p.url) === i);
      console.log(`  Total unique: ${uniqueProducts.length}`);

      for (const product of uniqueProducts) {
        try {
          const txId = await findOrCreateScrapedTransceiver({
            partNumber: product.partNumber,
            vendorId,
            formFactor: product.formFactor,
            speedGbps: product.speedGbps,
            speed: product.speed,
            reachMeters: product.reachMeters,
            reachLabel: product.reachLabel,
            fiberType: product.fiberType,
            wavelengths: product.wavelength,
            category: "DataCenter",
          });

          if (product.price && product.price > 0) {
            const hash = contentHash({ price: product.price, part: product.partNumber });
            const updated = await upsertPriceObservation({
              transceiverId: txId,
              sourceVendorId: vendorId,
              price: product.price,
              currency: "USD",
              stockLevel: "in_stock",
              url: product.url,
              contentHash: hash,
            });
            if (updated) priceUpdates++;
          }
          totalProducts++;
        } catch (err) {
          console.warn(`    DB error: ${(err as Error).message.slice(0, 80)}`);
        }
      }
    } catch (err) {
      console.error(`  Category failed: ${(err as Error).message}`);
    }

    await sleep(2000);
  }

  console.log(`\n=== OpticsBay Complete: ${totalProducts} products, ${priceUpdates} price updates ===`);
}

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