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

for (const product of listProducts()) {
  const sku = product.sku
  const { aspects, sw } = readPilotDoc(sku)
  const aspectRows = aspects.aspects || []
  const strengthRows = sw.items || []
  const seededBenefits = product.metafields?.pdpProductBenefits || []
  const profiles = aspectRows.length
    ? aspectRows.slice(0, 7).map((a: any, index: number) => {
      const matchingStrength = strengthRows.find((s: any) => String(s.insight || '').toLowerCase().includes(String(a.aspect || '').split(' ')[0]?.toLowerCase()))
      return {
        rank: index + 1,
        segment: a.customerJourney === 'Pre-Purchase' ? 'Pre-purchase evaluator' : 'Post-purchase routine user',
        motivation: a.aspect,
        sentiment: a.sentiment,
        reviewVolume: a.reviews || null,
        customerLanguage: a.exampleQuotes?.[0] || matchingStrength?.evidence || 'Seeded from Feefo theme; quote-level source review expansion available via supporting files where tagged.',
        contentUse: index === 0 ? 'Primary pdp.who_its_for framing' : 'Secondary benefit, FAQ, or comparison copy',
        source: `Feefo review-aspects rank ${a.rank}`,
        status: sourceStatus('amazon') === 'missing' && sourceStatus('reddit') === 'missing' ? 'feefo_seed_needs_external_validation' : 'ready_for_human_review'
      }
    })
    : seededBenefits.slice(0, 7).map((benefit: string, index: number) => ({
      rank: index + 1,
      segment: 'Product benefit evaluator',
      motivation: benefit,
      sentiment: 'needs_review',
      reviewVolume: null,
      customerLanguage: 'Seeded from product content; needs review-language expansion from Feefo/Amazon/Reddit before final copy.',
      contentUse: index === 0 ? 'Candidate PDP benefit framing' : 'Secondary benefit, FAQ, or comparison copy',
      source: 'product content benefits seed',
      status: 'source_seed_available_needs_review_language'
    }))
  writeJson(intelPath(sku, 'audience-profile.json'), {
    sku,
    name: aspects.name || product.name || sku,
    generatedAt: now(),
    generatedBy: 'extract-audience.ts',
    n: aspects.n || 0,
    sourceStatus: { feefo: 'available', amazonJv: sourceStatus('amazon'), amazonCompetitors: sourceStatus('amazon'), trustpilot: sourceStatus('trustpilot'), reddit: sourceStatus('reddit'), competitorPdp: sourceStatus('competitor-pdps') },
    coverage: aspectRows.length ? 'pilot_feefo_plus_external_sources' : 'catalogue_queue_seeded_from_product_content',
    profiles
  })
  console.log(`${sku}: wrote ${profiles.length} audience profiles`)
}
