/**
 * End-to-end capture smoke test.
 *
 * Pulls 2 sites off SOTD page 1 and runs the full pipeline against them:
 *   crawl → capture (Playwright) → descriptors → persist
 *
 * Run with:  bun run scripts/eye-ingest-capture-test.ts
 */

import { fetchGalleryPage } from '../src/services/designHarness/eyeIngester/crawler.js'
import { captureSite } from '../src/services/designHarness/eyeIngester/capturer.js'
import { deriveDescriptors } from '../src/services/designHarness/eyeIngester/descriptors.js'
import {
  buildInitialRecord,
  writeMotionDescriptors,
  writeSiteRecord,
} from '../src/services/designHarness/eyeIngester/storage.js'
import { DEFAULT_INGEST_CONFIG } from '../src/services/designHarness/eyeIngester/types.js'

async function main(): Promise<void> {
  const config = DEFAULT_INGEST_CONFIG
  const sites = await fetchGalleryPage('SOTD', 1, config)
  const subset = sites.slice(0, 2)

  process.stdout.write(`Targeting ${subset.length} sites for capture:\n`)
  for (const s of subset) process.stdout.write(`  - ${s.title} (${s.liveUrl})\n`)
  process.stdout.write('\n')

  for (const site of subset) {
    const label = `[${site.slug}]`
    const tStart = Date.now()
    process.stdout.write(`${label} capturing...\n`)

    try {
      const result = await captureSite(site, config)
      const descriptors = deriveDescriptors({
        durationMs: result.durationMs,
        frames: result.frames,
        hover: result.hover,
        canvases: result.canvases,
      })

      const record = buildInitialRecord(site)
      record.captureStatus = result.errors.length === 0 ? 'ok' : 'partial'
      record.captureErrors = result.errors
      record.files = {
        static: result.staticFile ? 'shot.webp' : undefined,
        motion: result.motionFile ? 'motion.webm' : undefined,
        keyframes: result.keyframeFiles.map(
          (_, i) => `keyframes/${String(i).padStart(2, '0')}.webp`,
        ),
      }

      await writeSiteRecord(record)
      await writeMotionDescriptors(site.slug, descriptors)

      const dt = ((Date.now() - tStart) / 1000).toFixed(1)
      process.stdout.write(`${label} ✓ captured in ${dt}s\n`)
      process.stdout.write(
        `        frames=${result.frames.length} keyframes=${result.keyframeFiles.length}\n`,
      )
      process.stdout.write(
        `        scrollLinkedRatio=${descriptors.scrollLinkedRatio.toFixed(3)}  ` +
          `fpsMedian=${descriptors.fpsMedian.toFixed(1)}  ` +
          `canvasCoverage=${descriptors.canvasCoverage.toFixed(2)}  ` +
          `easing=${descriptors.primaryEasing ?? 'none'}\n`,
      )
      if (result.errors.length > 0) {
        process.stdout.write(`        warnings: ${result.errors.join('; ')}\n`)
      }
    } catch (err: unknown) {
      process.stdout.write(
        `${label} ✗ failed: ${err instanceof Error ? err.message : String(err)}\n`,
      )
    }
  }
}

main().catch((err: unknown) => {
  process.stderr.write(
    `TEST FAILED: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`,
  )
  process.exit(1)
})
