/**
 * No-valid-competitor resolver.
 *
 * This is intentionally conservative. It only resolves products that already
 * have price/image/details evidence and where TIP cannot find any technically
 * strict, source-backed competitor candidate.
 *
 * Default is dry-run. Set NO_VALID_MATCH_APPLY=1 to write status/evidence.
 */
import { pool, checkAndSetFullyVerified, recordVerificationEvidence } from "./db";
import { logger } from "./logger";

const EXCLUDED_CATEGORIES = [
  "NonTransceiver",
  "Accessory",
  "Adapter / Converter",
  "Switch / Media Converter",
  "Switch / Network Infrastructure",
  "NIC / Adapter",
  "Mux / Passive Optical",
  "Product Family",
  "Loopback / Test Module",
];

type Candidate = {
  id: string;
  part_number: string;
  vendor_name: string;
  form_factor: string;
  speed_gbps: string;
  reach_meters: string | null;
  fiber_type: string | null;
  candidate_count: string;
  pending_equivalence_count: string;
};

function applyMode(): boolean {
  return process.env.NO_VALID_MATCH_APPLY === "1";
}

async function resolveNoValidCompetitors(): Promise<void> {
  const limit = Math.max(1, parseInt(process.env.NO_VALID_MATCH_LIMIT || "500", 10));
  const vendorFilter = process.env.NO_VALID_MATCH_VENDOR || "Flexoptix";
  const apply = applyMode();

  logger.info("=== No-valid-competitor resolver ===", { limit, vendorFilter, apply });

  const result = await pool.query<Candidate>(`
    WITH active AS (
      SELECT t.*, v.name AS vendor_name
      FROM transceivers t
      JOIN vendors v ON v.id = t.vendor_id
      WHERE COALESCE(t.data_confidence, 'unknown') != 'garbage'
        AND COALESCE(t.product_page_url, '') NOT LIKE '%/category/%'
        AND COALESCE(t.category, '') <> ALL($1::text[])
    ),
    ready AS (
      SELECT a.*
      FROM active a
      WHERE a.price_verified = true
        AND a.vendor_name ILIKE $2
        AND a.image_verified = true
        AND a.details_verified = true
        AND COALESCE(a.competitor_verified, false) = false
        AND COALESCE(a.competitor_status, 'needs_research') IN ('unknown', 'needs_research', 'ambiguous')
        AND a.form_factor IS NOT NULL
        AND a.form_factor != ''
        AND a.speed_gbps IS NOT NULL
        AND a.speed_gbps > 0
        AND a.reach_meters IS NOT NULL
        AND a.reach_meters > 0
        AND a.fiber_type IS NOT NULL
        AND a.fiber_type != ''
    ),
    scored AS (
      SELECT
        r.id,
        r.part_number,
        r.vendor_name,
        r.form_factor,
        r.speed_gbps,
        r.reach_meters,
        r.fiber_type,
        (
          SELECT COUNT(*)
          FROM active c
          WHERE c.id != r.id
            AND c.vendor_id != r.vendor_id
            AND c.price_verified = true
            AND c.image_verified = true
            AND c.details_verified = true
            AND c.form_factor = r.form_factor
            AND c.speed_gbps = r.speed_gbps
            AND UPPER(COALESCE(c.fiber_type, '')) = UPPER(COALESCE(r.fiber_type, ''))
            AND c.reach_meters IS NOT NULL
            AND c.reach_meters > 0
            AND ABS(c.reach_meters - r.reach_meters) <= GREATEST(25, r.reach_meters * 0.05)
            AND (
              COALESCE(NULLIF(regexp_replace(COALESCE(c.wavelengths, ''), '^.*?(\\d{3,4}).*$', '\\1'), COALESCE(c.wavelengths, '')), '') = ''
              OR COALESCE(NULLIF(regexp_replace(COALESCE(r.wavelengths, ''), '^.*?(\\d{3,4}).*$', '\\1'), COALESCE(r.wavelengths, '')), '') = ''
              OR ABS(
                NULLIF(regexp_replace(COALESCE(c.wavelengths, ''), '^.*?(\\d{3,4}).*$', '\\1'), COALESCE(c.wavelengths, ''))::int
                - NULLIF(regexp_replace(COALESCE(r.wavelengths, ''), '^.*?(\\d{3,4}).*$', '\\1'), COALESCE(r.wavelengths, ''))::int
              ) <= 15
            )
        ) AS candidate_count,
        (
          SELECT COUNT(*)
          FROM transceiver_equivalences eq
          WHERE eq.flexoptix_id = r.id
            AND eq.status IN ('pending', 'approved', 'auto_approved')
            AND eq.confidence >= 0.50
        ) AS pending_equivalence_count
      FROM ready r
    )
    SELECT *
    FROM scored
    WHERE candidate_count = 0
      AND pending_equivalence_count = 0
    ORDER BY vendor_name, part_number
    LIMIT $3
  `, [EXCLUDED_CATEGORIES, `%${vendorFilter}%`, limit]);

  logger.info("No-valid-match candidates", { count: result.rowCount ?? 0 });

  if (!apply) {
    for (const row of result.rows.slice(0, 30)) {
      logger.info("dry-run candidate", {
        vendor: row.vendor_name,
        partNumber: row.part_number,
        formFactor: row.form_factor,
        speedGbps: row.speed_gbps,
        reachMeters: row.reach_meters,
        fiberType: row.fiber_type,
      });
    }
    return;
  }

  let updated = 0;
  let fullyVerifiedEarned = 0;
  for (const row of result.rows) {
    const reason = [
      "Strict deterministic no-valid-match resolver found no source-backed competitor candidate",
      `same form_factor=${row.form_factor}`,
      `speed_gbps=${row.speed_gbps}`,
      `fiber_type=${row.fiber_type}`,
      `reach tolerance=max(25m,5%) around ${row.reach_meters}m`,
      "and no pending/approved equivalence above confidence 0.50",
    ].join("; ");

    const update = await pool.query(`
      UPDATE transceivers
      SET competitor_verified = true,
          competitor_verified_at = NOW(),
          competitor_status = 'no_valid_match',
          competitor_status_updated_at = NOW(),
          no_match_verified_at = NOW(),
          no_match_reason = $2,
          updated_at = NOW()
      WHERE id = $1
        AND COALESCE(competitor_verified, false) = false
      RETURNING id
    `, [row.id, reason]);

    if ((update.rowCount ?? 0) === 0) continue;

    await recordVerificationEvidence({
      transceiverId: row.id,
      verificationType: "competitor_no_match",
      evidenceValue: {
        reason,
        vendor: row.vendor_name,
        partNumber: row.part_number,
        candidateCount: Number(row.candidate_count),
        pendingEquivalenceCount: Number(row.pending_equivalence_count),
      },
      robotName: "verify:resolve-no-valid-competitor",
      confidence: 1,
    });

    if (await checkAndSetFullyVerified(row.id)) fullyVerifiedEarned++;
    updated++;
  }

  logger.info("No-valid-competitor resolver complete", {
    updated,
    fully_verified_earned: fullyVerifiedEarned,
  });
}

if (require.main === module) {
  resolveNoValidCompetitors()
    .then(() => pool.end())
    .catch((err) => {
      logger.error("No-valid-competitor resolver failed", { error: (err as Error).message });
      pool.end();
      process.exit(1);
    });
}
