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

const rawFiles = listJson(sourcePath('reddit'))
writeJson(sourcePath('reddit-status.json'), {
  generatedAt: now(),
  sourceType: 'reddit_import_status',
  status: rawFiles.length ? 'available' : 'missing',
  files: rawFiles,
  note: rawFiles.length ? 'Reddit source drops detected.' : 'Place Reddit thread/comment JSON exports in data/sources/reddit/. No synthetic Reddit evidence generated.'
})
console.log(`Reddit source files: ${rawFiles.length}`)

for (const product of listProducts()) {
  const sku = product.sku
  const { aspects, blockers } = readPilotDoc(sku)
  const seededBenefits = product.metafields?.pdpProductBenefits || []
  const pulses = (blockers.blockers || []).length
    ? blockers.blockers.slice(0, 7).map((item: any) => ({
      rank: item.rank,
      topic: item.blocker,
      whyItMatters: item.fix,
      expectedSubreddits: sku.includes('TURMERIC') ? ['r/Supplements', 'r/Biohackers', 'r/Arthritis'] : ['r/Supplements', 'r/VitaminD', 'r/Nutrition'],
      status: rawFiles.length ? 'ready_for_extraction' : 'needs_reddit_ingestion'
    }))
    : seededBenefits.slice(0, 7).map((benefit: string, index: number) => ({
      rank: index + 1,
      topic: benefit,
      whyItMatters: 'Seeded from product content; validate against deeper social listening before using as market-wide language.',
      expectedSubreddits: ['r/Supplements', 'r/Nutrition'],
      status: rawFiles.length ? 'source_seed_available_needs_sku_validation' : 'needs_reddit_ingestion'
    }))
  writeJson(intelPath(sku, 'reddit-pulse.json'), {
    sku,
    name: aspects.name || product.name || sku,
    generatedAt: now(),
    generatedBy: 'scrape-reddit.ts/import-normalizer',
    n: rawFiles.length,
    sourceStatus: { reddit: sourceStatus('reddit') },
    coverage: rawFiles.length ? 'catalogue_queue_seeded_from_limited_source_drop' : 'missing_source_drop',
    pulses
  })
  console.log(`${sku}: refreshed Reddit pulse queue`)
}
