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

const root = process.cwd()
const outRoot = join(root, 'content_population_exports')
const migrationOutRoot = join(root, '..', 'JV Migration to shopify', 'content_population_exports')

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 (Array.isArray(value)) value = value.join(' | ')
    if (value === undefined || value === null) value = ''
    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 existsLabel(path: string) {
  return existsSync(path) ? 'present' : 'missing'
}

const generatedAt = new Date().toISOString()
const handoff = readJson(join(outRoot, 'handoff_manifest.json'), {})
const readiness = readJson(join(outRoot, 'content_population_readiness.json'), {})
const assets = readJson(join(outRoot, 'asset_manifest_validation.json'), {})
const actionPlan = readJson(join(outRoot, 'handoff_action_plan.json'), {})
const blockers = handoff.blockerSummary || {}

const requiredFiles = [
  { file: 'products_content_matrixify.csv', owner: 'Dashboard export', path: join(outRoot, 'products_content_matrixify.csv') },
  { file: 'metaobjects_matrixify.csv', owner: 'Dashboard export', path: join(outRoot, 'metaobjects_matrixify.csv') },
  { file: 'smart_collections_matrixify.csv', owner: 'Dashboard export', path: join(outRoot, 'smart_collections_matrixify.csv') },
  { file: 'export_blockers.csv', owner: 'Dashboard export', path: join(outRoot, 'export_blockers.csv') },
  { file: 'products_content_v5.csv', owner: 'Migration emitter', path: join(migrationOutRoot, 'products_content_v5.csv') },
  { file: 'products_content_v5_blockers.csv', owner: 'Migration emitter', path: join(migrationOutRoot, 'products_content_v5_blockers.csv') },
  { file: 'metaobjects_all.csv', owner: 'Migration emitter', path: join(migrationOutRoot, 'metaobjects_all.csv') },
  { file: 'smart_collections_promo_cards.csv', owner: 'Migration emitter', path: join(migrationOutRoot, 'smart_collections_promo_cards.csv') },
  { file: 'asset_manifest_validation.csv', owner: 'Migration emitter', path: join(migrationOutRoot, 'asset_manifest_validation.csv') }
]

const preflightRows = [
  {
    Stage: 'Preflight',
    Check: 'Dashboard readiness audit',
    Owner: 'Dashboard owner',
    RequiredEvidence: '`bun run audit:content` exits 0 and content_population_readiness.json.ready is true.',
    CurrentStatus: readiness.ready ? 'pass' : 'blocked',
    CurrentEvidence: `${readiness.summary?.passing || 0}/${readiness.summary?.totalGates || 0} gates passing`,
    Blocking: readiness.ready ? 'no' : 'yes'
  },
  {
    Stage: 'Preflight',
    Check: 'Handoff manifest ready',
    Owner: 'Dashboard owner',
    RequiredEvidence: 'handoff_manifest.json.readyForLewis is true and export_blockers.csv has no rows.',
    CurrentStatus: handoff.readyForLewis ? 'pass' : 'blocked',
    CurrentEvidence: `readyForLewis=${Boolean(handoff.readyForLewis)}; blockers=${handoff.counts?.blockers ?? 'unknown'}`,
    Blocking: handoff.readyForLewis ? 'no' : 'yes'
  },
  {
    Stage: 'Preflight',
    Check: 'Asset uploads present',
    Owner: 'Design / Shopify Files',
    RequiredEvidence: 'validate_assets_manifest.py and bun run validate:assets report zero missing uploads/references.',
    CurrentStatus: assets.ready ? 'pass' : 'blocked',
    CurrentEvidence: `required=${assets.requiredCount ?? 'unknown'}; missingUploads=${assets.missingUploadCount ?? 'unknown'}; missingRefs=${assets.missingReferenceCount ?? 'unknown'}`,
    Blocking: assets.ready ? 'no' : 'yes'
  },
  {
    Stage: 'Preflight',
    Check: 'Owner action plan closed',
    Owner: 'Project owner',
    RequiredEvidence: 'handoff_action_plan.json.ready is true or all listed owners have supplied required evidence.',
    CurrentStatus: actionPlan.ready ? 'pass' : 'blocked',
    CurrentEvidence: `actions=${actionPlan.counts?.actions ?? 0}; p0=${actionPlan.counts?.p0 ?? 0}`,
    Blocking: actionPlan.ready ? 'no' : 'yes'
  },
  ...requiredFiles.map(item => ({
    Stage: 'Preflight',
    Check: `${item.owner} file: ${item.file}`,
    Owner: item.owner,
    RequiredEvidence: `${item.file} exists and is the current regenerated output.`,
    CurrentStatus: existsLabel(item.path),
    CurrentEvidence: item.path,
    Blocking: existsSync(item.path) ? 'no' : 'yes'
  }))
]

const stagingRows = [
  {
    Stage: 'Matrixify import',
    Check: 'Import metaobjects first',
    Owner: 'Lewis/Euan',
    RequiredEvidence: 'Matrixify staging import log for metaobjects has no failed rows; definitions include dietary_tag, health_goals, key_ingredients, benefits, clinically_shown_to, promo_card.',
    CurrentStatus: 'not_started',
    CurrentEvidence: 'No staging import log captured in repo.',
    Blocking: 'yes'
  },
  {
    Stage: 'Matrixify import',
    Check: 'Import smart collection promo-card mappings',
    Owner: 'Lewis/Euan',
    RequiredEvidence: 'Matrixify staging import log for smart_collections_promo_cards.csv has no failed rows and both mapped collections reference promo_card handles.',
    CurrentStatus: 'not_started',
    CurrentEvidence: `smartCollectionRows=${handoff.counts?.smartCollectionRows ?? 'unknown'}`,
    Blocking: 'yes'
  },
  {
    Stage: 'Matrixify import',
    Check: 'Import product/variant metafields',
    Owner: 'Lewis/Euan',
    RequiredEvidence: 'Matrixify staging import log for products_content_v5.csv has no failed rows; variant rows match expected 350.',
    CurrentStatus: 'not_started',
    CurrentEvidence: `variantRows=${handoff.counts?.variantRows ?? 'unknown'}`,
    Blocking: 'yes'
  },
  {
    Stage: 'PDP spot-check',
    Check: 'Spot-check 5-10 PDPs after staging import',
    Owner: 'Dashboard owner + Lewis/Euan',
    RequiredEvidence: 'Documented pass/fail checks for metafields, metaobject refs, image/file refs, FAQ fields, variant cards, promo cards, and collection mapping.',
    CurrentStatus: 'not_started',
    CurrentEvidence: 'No PDP staging URL/checklist evidence captured yet.',
    Blocking: 'yes'
  },
  {
    Stage: 'Cutover',
    Check: 'Production cutover approval',
    Owner: 'Umar / JV',
    RequiredEvidence: 'Human approval that staging PDP checks passed and remaining known risks are accepted.',
    CurrentStatus: 'not_started',
    CurrentEvidence: `approval blockers=${blockers.approval ?? 'unknown'}`,
    Blocking: 'yes'
  }
]

const rows = [...preflightRows, ...stagingRows]
const manifest = {
  generatedAt,
  ready: rows.every(row => row.CurrentStatus === 'pass' || (row.Stage === 'Preflight' && row.CurrentStatus === 'present')),
  counts: {
    checks: rows.length,
    blocking: rows.filter(row => row.Blocking === 'yes').length,
    preflight: preflightRows.length,
    staging: stagingRows.length,
    requiredFiles: requiredFiles.length
  },
  blockerSummary: blockers,
  checks: rows
}

writeFileSync(join(outRoot, 'staging_import_checklist.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf8')
writeFileSync(join(outRoot, 'staging_import_checklist.csv'), csv(rows, ['Stage', 'Check', 'Owner', 'RequiredEvidence', 'CurrentStatus', 'CurrentEvidence', 'Blocking']), 'utf8')

const md = [
  '# JV staging import checklist',
  '',
  `Generated: ${generatedAt}`,
  '',
  'Use this only after the dashboard handoff pack is clean. It separates preflight evidence from Lewis/Euan staging import evidence so missing live checks cannot be mistaken for completed work.',
  '',
  '## Current state',
  `- Ready: ${manifest.ready ? 'YES' : 'NO'}`,
  `- Checks: ${manifest.counts.checks}`,
  `- Blocking checks: ${manifest.counts.blocking}`,
  `- Export blockers: ${handoff.counts?.blockers ?? 'unknown'}`,
  `- Missing asset uploads/files: ${assets.missingUploadCount ?? 'unknown'}`,
  '',
  '## Checklist',
  ...rows.map(row => [
    `### ${row.Stage} - ${row.Check}`,
    `- Owner: ${row.Owner}`,
    `- Required evidence: ${row.RequiredEvidence}`,
    `- Current status: ${row.CurrentStatus}`,
    `- Current evidence: ${row.CurrentEvidence}`,
    `- Blocking: ${row.Blocking}`,
    ''
  ].join('\n')),
  '## Completion rule',
  'Do not approve production cutover until every preflight check passes, Matrixify staging imports have clean logs, and 5-10 PDP spot checks are recorded.',
  ''
].join('\n')
writeFileSync(join(outRoot, 'staging_import_checklist.md'), md, 'utf8')

console.log(`Staging checklist ready: ${manifest.ready}`)
console.log(`Checks: ${manifest.counts.checks}`)
console.log(`Blocking checks: ${manifest.counts.blocking}`)
if (!manifest.ready) process.exitCode = 1
