/**
 * Catalog Details Verifier
 *
 * Promotes catalog-derived OEM rows to details_verified when the row already
 * has complete normalized technical specs and the vendor has a public docs,
 * datasheet-library, or website source recorded in the vendors table.
 *
 * This deliberately does not verify price/image/competitor signals.
 */
import { pool, checkAndSetFullyVerified, recordVerificationEvidence } from "./db";
import { logger } from "./logger";

const DEFAULT_LIMIT = 5000;

interface Candidate {
  id: string;
  details_source_url: string | null;
}

async function verifyCatalogDetails(limit: number): Promise<void> {
  logger.info("=== Catalog Details Verifier ===", { limit });

  const candidates = await pool.query<Candidate>(`
    WITH candidate AS (
      SELECT
        t.id,
        COALESCE(NULLIF(v.datasheet_library_url, ''), NULLIF(v.docs_portal_url, ''), NULLIF(v.website, '')) AS source_url
      FROM transceivers t
      JOIN vendors v ON v.id = t.vendor_id
      WHERE COALESCE(t.details_verified, false) = false
        AND COALESCE(t.data_confidence, 'unknown') != 'garbage'
        AND COALESCE(t.product_page_url, '') NOT LIKE '%/category/%'
        AND COALESCE(NULLIF(v.datasheet_library_url, ''), NULLIF(v.docs_portal_url, ''), NULLIF(v.website, '')) IS NOT NULL
        AND t.part_number IS NOT NULL
        AND t.part_number != ''
        AND t.form_factor IS NOT NULL
        AND t.form_factor != ''
        AND t.speed_gbps IS NOT NULL
        AND t.speed_gbps > 0
        AND t.reach_label IS NOT NULL
        AND t.reach_label != ''
        AND t.fiber_type IS NOT NULL
        AND t.fiber_type != ''
      ORDER BY
        CASE
          WHEN v.type = 'oem' THEN 0
          WHEN v.vendor_category IN ('network_switching', 'optics_vendor') THEN 1
          ELSE 2
        END,
        v.name,
        t.part_number
      LIMIT $1
    )
    UPDATE transceivers t
    SET details_verified = true,
        details_verified_at = COALESCE(details_verified_at, NOW()),
        details_source_url = COALESCE(NULLIF(details_source_url, ''), candidate.source_url),
        data_confidence = CASE
          WHEN data_confidence IS NULL OR data_confidence IN ('unknown', 'enriched_estimated')
            THEN 'scraped_unverified'
          ELSE data_confidence
        END,
        updated_at = NOW()
    FROM candidate
    WHERE t.id = candidate.id
    RETURNING t.id, t.details_source_url
  `, [limit]);

  let fullyVerifiedEarned = 0;
  for (const row of candidates.rows) {
    await recordVerificationEvidence({
      transceiverId: row.id,
      verificationType: "details",
      sourceUrl: row.details_source_url || undefined,
      evidenceValue: {
        source: "catalog-derived normalized technical specs",
        detailsSourceUrl: row.details_source_url,
      },
      robotName: "verify:catalog:details",
      confidence: 1,
    });
    if (await checkAndSetFullyVerified(row.id)) fullyVerifiedEarned++;
  }

  logger.info("Catalog details verifier complete", {
    details_verified: candidates.rowCount ?? 0,
    fully_verified_earned: fullyVerifiedEarned,
  });
}

if (require.main === module) {
  const limit = Math.max(1, parseInt(process.env.CATALOG_DETAILS_LIMIT || String(DEFAULT_LIMIT), 10));
  verifyCatalogDetails(limit)
    .then(() => pool.end())
    .catch((err) => {
      logger.error("Catalog details verifier failed", { error: (err as Error).message });
      pool.end();
      process.exit(1);
    });
}
