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

const root = process.cwd()
const outRoot = join(root, 'content_population_exports')

const checks = [
  { name: 'export_content', command: ['bun', 'run', 'export:content'], requiredForReady: true },
  { name: 'validate_assets', command: ['bun', 'run', 'validate:assets'], requiredForReady: true },
  { name: 'validate_template', command: ['bun', 'run', 'validate:template'], requiredForReady: true },
  { name: 'source_request_pack', command: ['bun', 'run', 'source:pack'], requiredForReady: true },
  { name: 'validate_sources', command: ['bun', 'run', 'validate:sources'], requiredForReady: true },
  { name: 'validate_claims', command: ['bun', 'run', 'validate:claims'], requiredForReady: true },
  { name: 'clinical_blank_decisions', command: ['bun', 'run', 'compliance:blank-decisions'], requiredForReady: true },
  { name: 'intelligence_queue', command: ['bun', 'run', 'intelligence:queue'], requiredForReady: true },
  { name: 'product_approval_decisions', command: ['bun', 'run', 'approval:decisions'], requiredForReady: true },
  { name: 'product_approval_review_packet', command: ['bun', 'run', 'approval:review-packet'], requiredForReady: true },
  { name: 'handoff_actions', command: ['bun', 'run', 'handoff:actions'], requiredForReady: true },
  { name: 'executive_decision_brief', command: ['bun', 'run', 'handoff:decision-brief'], requiredForReady: true },
  { name: 'staging_handoff_packet', command: ['bun', 'run', 'staging:handoff-packet'], requiredForReady: true },
  { name: 'staging_evidence', command: ['bun', 'run', 'staging:evidence'], requiredForReady: true },
  { name: 'staging_checklist', command: ['bun', 'run', 'staging:checklist'], requiredForReady: true },
  { name: 'delivery_index', command: ['bun', 'run', 'delivery:index'], requiredForReady: true },
  { name: 'content_audit', command: ['bun', 'run', 'audit:content'], requiredForReady: true }
]

function csv(rows: any[], headers: string[]) {
  const esc = (value: any) => {
    if (value === undefined || value === null) value = ''
    value = Array.isArray(value) ? value.join(' | ') : 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'
}

const generatedAt = new Date().toISOString()
const results = []

for (const check of checks) {
  const startedAt = new Date().toISOString()
  const proc = Bun.spawnSync({
    cmd: check.command,
    cwd: root,
    stdout: 'pipe',
    stderr: 'pipe'
  })
  const stdout = proc.stdout ? new TextDecoder().decode(proc.stdout).trim() : ''
  const stderr = proc.stderr ? new TextDecoder().decode(proc.stderr).trim() : ''
  results.push({
    Name: check.name,
    Command: check.command.join(' '),
    ExitCode: proc.exitCode,
    Status: proc.exitCode === 0 ? 'pass' : 'blocked',
    RequiredForReady: check.requiredForReady ? 'yes' : 'no',
    StartedAt: startedAt,
    FinishedAt: new Date().toISOString(),
    Stdout: stdout,
    Stderr: stderr
  })
  console.log(`${check.name}: ${proc.exitCode === 0 ? 'pass' : 'blocked'} (${proc.exitCode})`)
}

const ready = results.every(row => row.ExitCode === 0)
const report = {
  generatedAt,
  ready,
  objective: 'JV Shopify content population handoff readiness',
  counts: {
    checks: results.length,
    passing: results.filter(row => row.ExitCode === 0).length,
    blocked: results.filter(row => row.ExitCode !== 0).length
  },
  checks: results
}

writeFileSync(join(outRoot, 'handoff_verification_run.json'), JSON.stringify(report, null, 2) + '\n', 'utf8')
writeFileSync(join(outRoot, 'handoff_verification_run.csv'), csv(results.map(row => ({
  Name: row.Name,
  Command: row.Command,
  Status: row.Status,
  ExitCode: row.ExitCode,
  RequiredForReady: row.RequiredForReady,
  Stdout: row.Stdout.split('\n').slice(0, 5).join(' | '),
  Stderr: row.Stderr.split('\n').slice(0, 5).join(' | ')
})), ['Name', 'Command', 'Status', 'ExitCode', 'RequiredForReady', 'Stdout', 'Stderr']), 'utf8')

const md = [
  '# JV handoff verification run',
  '',
  `Generated: ${generatedAt}`,
  '',
  `Ready: **${ready ? 'YES' : 'NO'}**`,
  '',
  `Checks passing: ${report.counts.passing}/${report.counts.checks}`,
  '',
  '## Checks',
  ...results.map(row => `- ${row.ExitCode === 0 ? '[PASS]' : '[BLOCKED]'} ${row.Name}: \`${row.Command}\` exit=${row.ExitCode}`),
  '',
  '## Completion rule',
  'This run must be all PASS before the handoff can be considered ready. Expected blocked checks are still blockers, not successful completion.',
  ''
].join('\n')
writeFileSync(join(outRoot, 'handoff_verification_run.md'), md, 'utf8')

console.log(`Handoff verification ready: ${ready}`)
console.log(`Checks passing: ${report.counts.passing}/${report.counts.checks}`)
if (!ready) process.exitCode = 1
