#!/usr/bin/env bun
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import { join } from 'path'

const root = process.cwd()
const outRoot = join(root, 'content_population_exports')
mkdirSync(outRoot, { recursive: true })

function readJson(path: string, fallback: any = null) {
  if (!existsSync(path)) return fallback
  return JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''))
}
function csv(rows: any[], headers: string[]) {
  const esc = (value: any) => {
    if (value === undefined || value === null) value = ''
    if (Array.isArray(value)) value = value.join(' | ')
    value = String(value)
    return /[",\n\r]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
  }
  return [headers.join(','), ...rows.map(row => headers.map(header => esc(row[header])).join(','))].join('\n') + '\n'
}
function line(text: any) { return String(text || '').trim() }

const generatedAt = new Date().toISOString()
const workbook = readJson(join(outRoot, 'reviewer_decision_workbook.json'), {})
const preflight = readJson(join(outRoot, 'reviewer_input_preflight.json'), {})
const dailyFiles = existsSync(outRoot)
  ? Array.from(new Bun.Glob('daily_status_*.json').scanSync({ cwd: outRoot })).sort()
  : []
const daily = dailyFiles.length ? readJson(join(outRoot, dailyFiles.at(-1) as string), {}) : {}
const verifier = readJson(join(outRoot, 'handoff_verification_run.json'), {})
const delivery = readJson(join(outRoot, 'delivery_index.json'), {})
const dataforseo = readJson(join(outRoot, 'dataforseo_live_connection.json'), {})
const statusLine = `Handoff remains blocked: ${workbook.counts?.totalRemaining ?? 'unknown'} evidence items remaining; verification ${verifier.counts?.passing ?? daily.verification?.passing ?? 'unknown'}/${verifier.counts?.checks ?? daily.verification?.checks ?? 'unknown'} passing; delivery packet ${delivery.counts?.present ?? daily.deliveryIndex?.present ?? 'unknown'}/${delivery.counts?.files ?? daily.deliveryIndex?.files ?? 'unknown'} present.`

const laneMeta: Record<string, { audience: string, channel: string, ask: string }> = {
  'Compliance blank/source-backed claim decisions': {
    audience: 'Compliance owner / Umar',
    channel: 'Compliance review handoff',
    ask: 'Please either approve the SKU to ship with the clinical claim field blank, or provide source-backed claim evidence and refs. Do not add generic health claims.'
  },
  'Product approval decisions': {
    audience: 'Umar / JV reviewer',
    channel: 'Product approval handoff',
    ask: 'Please review content, compliance, images, export readiness, and supporting evidence for each SKU before setting approve_all.'
  },
  'Lewis/Euan staging import evidence': {
    audience: 'Lewis/Euan + dashboard owner',
    channel: 'Staging import handoff',
    ask: 'Please run/record the staging import evidence: clean import logs, real PDP spot checks, and signed cutover approval after checks pass.'
  },
  'DataForSEO Reviews endpoint/support/spend clearance': {
    audience: 'Research / project owner',
    channel: 'Provider clearance handoff',
    ask: 'Please wait for DataForSEO Reviews endpoint clearance, record support response, then explicitly approve the capped Stage 1 spend only if the endpoint is retry-safe.'
  }
}

function normalisePath(value: string) {
  return String(value || '').replace(/\\/g, '/').replace(/\/+$/, '').trim()
}
function matchesEditableFile(editableFile: string, blockerFile: string) {
  const editable = normalisePath(editableFile)
  const blocker = normalisePath(blockerFile)
  if (!editable || !blocker) return false
  return editable === blocker || editable.startsWith(`${blocker}/`) || blocker.startsWith(`${editable}/`)
}
const messages = (workbook.ownerRows || []).map((lane: any, index: number) => {
  const meta = laneMeta[lane.Lane] || { audience: lane.Owner, channel: 'Reviewer handoff', ask: lane.AcceptedCompletion }
  const files = String(lane.EditableFile || '').split(';').flatMap(part => part.split(',')).map(part => part.trim()).filter(Boolean)
  const matchingPreflight = (preflight.blockingRows || []).filter((row: any) =>
    files.some(file => matchesEditableFile(file, row.File))
  )
  const blockerEvidence = matchingPreflight.length
    ? matchingPreflight.map((row: any) => `${row.Area}: ${row.Evidence}`).join(' | ')
    : `${lane.RemainingCount} item(s) remain in this lane.`
  const subject = `[JV handoff] ${lane.Lane} - ${lane.RemainingCount} remaining`
  const body = [
    `Hi ${meta.audience},`,
    '',
    `Current JV dashboard handoff status: ${statusLine}`,
    '',
    `Your lane: ${lane.Lane}`,
    `Remaining: ${lane.RemainingCount}`,
    `Ask: ${meta.ask}`,
    '',
    `Editable file(s): ${lane.EditableFile}`,
    `Review packet: ${lane.ReviewPacket}`,
    `Required fields/evidence: ${lane.RequiredFields}`,
    '',
    `Current preflight evidence: ${blockerEvidence}`,
    '',
    `After updating the file/evidence, rerun: ${lane.RegenerateCommand}`,
    '',
    `Guardrail: ${lane.Guardrail}`,
    '',
    'Please do not approve, infer, or backfill anything unless the evidence is actually reviewed and recorded in the editable file above.'
  ].join('\n')
  return {
    Sequence: index + 1,
    Audience: meta.audience,
    Channel: meta.channel,
    Lane: lane.Lane,
    Subject: subject,
    RemainingCount: lane.RemainingCount,
    EditableFile: lane.EditableFile,
    ReviewPacket: lane.ReviewPacket,
    RequiredFields: lane.RequiredFields,
    PreflightEvidence: blockerEvidence,
    RegenerateCommand: lane.RegenerateCommand,
    Guardrail: lane.Guardrail,
    MessageBody: body
  }
})

const manifest = {
  generatedAt,
  ready: false,
  purpose: 'Copy-paste owner handoff messages for the remaining compliance, approval, staging, and provider-spend blockers. This assigns evidence-producing next actions without approving anything.',
  status: statusLine,
  counts: {
    messages: messages.length,
    totalRemaining: workbook.counts?.totalRemaining ?? messages.reduce((sum: number, row: any) => sum + Number(row.RemainingCount || 0), 0),
    verifierPassing: verifier.counts?.passing ?? null,
    verifierChecks: verifier.counts?.checks ?? null,
    deliveryPresent: delivery.counts?.present ?? null,
    deliveryFiles: delivery.counts?.files ?? null,
    dataforseoAccountStatus: dataforseo.accountConnection?.status_code ?? null,
    credentialPrinted: dataforseo.credentialPrinted ?? null
  },
  guardrails: [
    'Do not self-approve compliance blanks or product approvals.',
    'Do not treat queued staging checks as completed evidence.',
    'Do not run paid DataForSEO Reviews while the endpoint/support/spend gates are blocked.',
    'Use the real pi-fresh-foundation .env credentials only through shell environment; never print or paste secrets.'
  ],
  messages,
  files: {
    markdown: 'content_population_exports/owner_handoff_messages.md',
    json: 'content_population_exports/owner_handoff_messages.json',
    csv: 'content_population_exports/owner_handoff_messages.csv'
  }
}

writeFileSync(join(outRoot, 'owner_handoff_messages.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf8')
writeFileSync(join(outRoot, 'owner_handoff_messages.csv'), csv(messages, ['Sequence', 'Audience', 'Channel', 'Lane', 'Subject', 'RemainingCount', 'EditableFile', 'ReviewPacket', 'RequiredFields', 'PreflightEvidence', 'RegenerateCommand', 'Guardrail', 'MessageBody']), 'utf8')
writeFileSync(join(outRoot, 'owner_handoff_messages.md'), [
  '# Owner handoff messages',
  '',
  `Generated: ${generatedAt}`,
  '',
  manifest.status,
  '',
  `Messages: ${manifest.counts.messages}`,
  `Tracked remaining items: ${manifest.counts.totalRemaining}`,
  `Verifier: ${manifest.counts.verifierPassing}/${manifest.counts.verifierChecks} passing`,
  `Delivery packet: ${manifest.counts.deliveryPresent}/${manifest.counts.deliveryFiles} present`,
  `DataForSEO account status: ${manifest.counts.dataforseoAccountStatus}; credentialPrinted=${manifest.counts.credentialPrinted}`,
  '',
  'These are copy-paste prompts for the owners who must produce the remaining evidence. They do not approve content, close gates, or unlock provider spend.',
  '',
  '## Guardrails',
  ...manifest.guardrails.map(item => `- ${item}`),
  '',
  '## Messages',
  ...messages.flatMap((message: any) => [
    `### ${message.Sequence}. ${message.Channel}`,
    '',
    `**To:** ${message.Audience}`,
    `**Subject:** ${message.Subject}`,
    '',
    '```text',
    message.MessageBody,
    '```',
    ''
  ]),
  ''
].join('\n'), 'utf8')

console.log(`Owner handoff messages ready: ${manifest.ready}`)
console.log(`Messages: ${manifest.counts.messages}`)
console.log(`Tracked remaining items: ${manifest.counts.totalRemaining}`)
