#!/usr/bin/env bun
import { intelPath, listProducts, readPilotDoc, sourcePath, listJson, sourceStatus, writeJson, now } from './lib/intel-utils'

const rawFiles = listJson(sourcePath('amazon'))
writeJson(sourcePath('amazon-status.json'), {
  generatedAt: now(),
  sourceType: 'amazon_import_status',
  status: rawFiles.length ? 'available' : 'missing',
  files: rawFiles,
  note: rawFiles.length ? 'Raw Amazon source drops detected. Extraction hooks can map rows into per-SKU themes.' : 'Place Amazon JV/competitor JSON exports in data/sources/amazon/. No synthetic Amazon evidence generated.'
})
console.log(`Amazon source files: ${rawFiles.length}`)

for (const product of listProducts()) {
  const sku = product.sku
  const { aspects, improvements } = readPilotDoc(sku)
  const seededBenefits = product.metafields?.pdpProductBenefits || []
  const themes = (improvements.improvements || []).length
    ? improvements.improvements.slice(0, 7).map((item: any) => ({
      rank: item.rank,
      theme: item.productWeakness || item.improvement,
      jvFeefoSignal: item.improvement,
      expectedAmazonCheck: 'Confirm whether Amazon shoppers mention the same issue before using as market-wide evidence.',
      status: rawFiles.length ? 'ready_for_extraction' : 'needs_amazon_ingestion'
    }))
    : seededBenefits.slice(0, 7).map((benefit: string, index: number) => ({
      rank: index + 1,
      theme: benefit,
      jvFeefoSignal: 'Seeded from product content; no per-SKU Amazon extraction yet.',
      expectedAmazonCheck: 'Use as an extraction queue only until deeper Amazon evidence is captured for this SKU/category.',
      status: rawFiles.length ? 'source_seed_available_needs_sku_validation' : 'needs_amazon_ingestion'
    }))
  writeJson(intelPath(sku, 'amazon-reviews.json'), {
    sku,
    name: aspects.name || product.name || sku,
    generatedAt: now(),
    generatedBy: 'scrape-amazon.ts/import-normalizer',
    n: rawFiles.length,
    sourceStatus: { amazonJv: sourceStatus('amazon'), amazonCompetitors: sourceStatus('amazon') },
    coverage: rawFiles.length ? 'catalogue_queue_seeded_from_limited_source_drop' : 'missing_source_drop',
    themes
  })
  console.log(`${sku}: refreshed Amazon review queue`)
}
