/**
 * Re-shoot the app for the press kit.
 *
 * The screenshots shipped in this kit are from an older build. This script takes a
 * fresh set from whatever is running locally, at a fixed viewport and 2x density,
 * with no browser chrome.
 *
 * It cannot do the whole job alone. Anything that moves funds or authorizes an agent
 * needs a passkey, and only the wallet owner can approve that. So the script opens a
 * real (non-headless) browser, walks to each screen, and pauses when it needs you.
 *
 *   1. cd ../../bvcc_wallet && npm run dev
 *   2. node scripts/capture-screenshots.mjs
 *   3. approve with Face ID / fingerprint when it asks, then press Enter here
 *
 * Output lands in screenshots/raw/ and screenshots/web/.
 */

import { chromium } from 'playwright'
import { existsSync, readdirSync, mkdirSync } from 'fs'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { homedir } from 'os'
import readline from 'readline'

const here = dirname(fileURLToPath(import.meta.url))
const kit = join(here, '..')
const RAW = join(kit, 'screenshots', 'raw')
const WEB = join(kit, 'screenshots', 'web')
mkdirSync(RAW, { recursive: true })
mkdirSync(WEB, { recursive: true })

const BASE = process.env.BVCC_URL || 'http://localhost:3000'

// Reuse whatever Chromium is already in the Playwright cache.
function cachedChromium() {
  const cache = join(homedir(), '.cache', 'ms-playwright')
  if (!existsSync(cache)) return undefined
  for (const b of readdirSync(cache)
    .filter(d => d.startsWith('chromium-'))
    .sort((a, z) => Number(z.split('-')[1]) - Number(a.split('-')[1]))) {
    const exe = join(cache, b, 'chrome-linux64', 'chrome')
    if (existsSync(exe)) return exe
  }
}

const ask = q =>
  new Promise(res => {
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
    rl.question(q, a => {
      rl.close()
      res(a)
    })
  })

/* Each shot: where to go, what to call it, and whether a human has to act first.
   Keep `manual` honest — if a screen needs real funds or a passkey, say so. */
const SHOTS = [
  { path: '/', name: 'landing', manual: false, note: 'Marketing landing, hero' },
  { path: '/wallet', name: 'overview', manual: true, note: 'Sign in first. Mainnet, with a real balance.' },
  { path: '/wallet/agents', name: 'agents', manual: true, note: 'An authorized agent with visible spend.' },
  { path: '/wallet/positions', name: 'positions', manual: true, note: 'At least one open LP position.' },
  { path: '/wallet/allowances', name: 'allowances', manual: true, note: 'Approvals list, ideally one unlimited.' },
  { path: '/wallet/swap', name: 'swap', manual: true, note: 'An amount filled in so the quote shows.' },
  { path: '/docs/connect-ai', name: 'docs-connect-ai', manual: false, note: 'MCP onboarding docs' },
]

const exe = cachedChromium()
const browser = await chromium.launch({ headless: false, executablePath: exe })
const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 }, deviceScaleFactor: 2 })
const page = await ctx.newPage()
// Second context at 1x shares the same profile, so a session signed in on `page`
// is already signed in here and the web-sized shot needs no second approval.
const webPage = await ctx.newPage()
await webPage.setViewportSize({ width: 1600, height: 1000 })

console.log(`\nShooting ${BASE} at 1600x1000 @2x\n`)

for (const s of SHOTS) {
  await page.goto(BASE + s.path, { waitUntil: 'networkidle' }).catch(() => {})
  await page.waitForTimeout(1200)

  if (s.manual) {
    console.log(`\n  ${s.name} — ${s.note}`)
    const a = await ask('  Set the screen up, then press Enter (or "s" to skip): ')
    if (a.trim().toLowerCase() === 's') {
      console.log('  skipped')
      continue
    }
  }

  // Load every lazy image before shooting.
  await page.evaluate(async () => {
    document.querySelectorAll('img').forEach(i => (i.loading = 'eager'))
    await Promise.all(
      [...document.images].filter(i => !i.complete).map(i => new Promise(r => { i.onload = i.onerror = r })),
    )
  })

  // Raw is 2x (3200px wide) for print and zooming; web is 1x for articles.
  await page.screenshot({ path: join(RAW, `${s.name}.png`) })
  await webPage.goto(BASE + s.path, { waitUntil: 'networkidle' }).catch(() => {})
  await webPage.waitForTimeout(800)
  await webPage.screenshot({ path: join(WEB, `${s.name}.png`) })

  console.log(`  ✓ ${s.name}.png`)
}

await browser.close()
console.log('\nDone. 2x in screenshots/raw/, 1x in screenshots/web/.')
console.log('Copy the web set into bvcc_wallet/public/press/shots/ and rebuild the zip.\n')
