/**
 * Browser truth: the portal's own CSS rendered by headless Chrome at device scale 1.
 * Pages are local files under out/bench/html/; nothing touches the network.
 */
import { spawnSync } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'

import { extractRules } from './css'
import { decodePng, type Image } from './png'

export const CHROME = process.env.BENCH_CHROME ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe'

const FONT_FACES: [file: string, weight: number][] = [
  ['TitilliumWeb-Regular.ttf', 400],
  ['TitilliumWeb-SemiBold.ttf', 600],
  ['TitilliumWeb-Bold.ttf', 700],
]

export interface BrowserPage {
  name: string
  size: [number, number]
  background: string
  html: string
  selectors: string[]
  css?: string
  state?: 'hover' | 'active' | 'focus'
}

export function buildPage(page: BrowserPage, portalCss: string, root: string, installDir: string): string {
  const fileUrl = (p: string) => pathToFileURL(p).href
  const faces = FONT_FACES.map(([file, weight]) =>
    `@font-face { font-family: 'Titillium Web'; font-weight: ${weight}; src: url('${fileUrl(path.join(installDir, 'data/core/fonts', file))}'); }`).join('\n')
  const rules = page.selectors.length ? extractRules(portalCss, page.selectors, (u) => fileUrl(path.join(root, u))) : ''
  const [w, h] = page.size
  const state = page.state
    ? `<script>for (const e of document.querySelectorAll('[data-bench]')) e.classList.add('is-${page.state}')</script>`
    : ''
  return `<!doctype html>
<html><head><meta charset="utf-8">
<style>
${faces}
html, body { margin: 0; padding: 0; overflow: hidden; }
body { font-family: 'Titillium Web'; font-size: 14px; color: #fff; }
#bench-root { position: absolute; left: 0; top: 0; width: ${w}px; height: ${h}px; background: ${page.background};
  display: flex; flex-direction: column; align-items: flex-start; overflow: hidden; }
</style>
<style>
/* verbatim from docs/reference/portal-css.txt (pseudo-classes rewritten) */
${rules}
</style>
<style>
${page.css ?? ''}
</style>
</head><body><div id="bench-root">${page.html}</div>${state}</body></html>
`
}

/** Render `htmlFile` to a W×H PNG. Uses a private profile so the owner's Chrome is untouched. */
export function chromeShot(htmlFile: string, size: [number, number], outPng: string, profileDir: string): Image {
  if (!existsSync(CHROME)) throw new Error(`Chrome not found at ${CHROME} (set BENCH_CHROME)`)
  if (existsSync(outPng)) rmSync(outPng)
  const [w, h] = size
  const args = [
    '--headless=new', '--force-device-scale-factor=1', '--hide-scrollbars', '--disable-gpu',
    '--no-first-run', '--no-default-browser-check', '--disable-extensions', '--allow-file-access-from-files',
    '--run-all-compositor-stages-before-draw', '--virtual-time-budget=2000',
    `--user-data-dir=${profileDir}`, `--screenshot=${outPng}`, `--window-size=${w},${h}`, pathToFileURL(htmlFile).href,
  ]
  const res = spawnSync(CHROME, args, { encoding: 'utf8', timeout: 60_000, windowsHide: true })
  if (!existsSync(outPng)) throw new Error(`chrome produced no screenshot (exit ${res.status}): ${res.stderr?.slice(-400)}`)
  const img = decodePng(readFileSync(outPng))
  if (img.width !== w || img.height !== h) throw new Error(`chrome screenshot is ${img.width}x${img.height}, wanted ${w}x${h}`)
  return img
}

export function renderBrowser(page: BrowserPage, opts: { root: string; installDir: string; portalCss: string; outPng: string }): Image {
  const htmlDir = path.join(opts.root, 'out/bench/html')
  mkdirSync(htmlDir, { recursive: true })
  const htmlFile = path.join(htmlDir, `${page.name}.html`)
  writeFileSync(htmlFile, buildPage(page, opts.portalCss, opts.root, opts.installDir))
  return chromeShot(htmlFile, page.size, opts.outPng, path.join(opts.root, 'out/bench/chrome-profile'))
}
