import { existsSync } from 'node:fs'
import { mkdir, writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { createServer as createViteServer } from 'vite'
import { chromium } from '../cnc_wams_gpt6/linuxcnc-master/web/node_modules/playwright/index.mjs'

const root = resolve(new URL('..', import.meta.url).pathname)
const reportPath = resolve(root, 'config/chrome-cam-linuxcnc-machine-verification.json')
const executable = process.env.CHROME_BIN || '/home/mes123456/.local/bin/google-chrome'
if (!existsSync(executable)) throw new Error(`Chrome executable is unavailable: ${executable}`)

const vite = await createViteServer({
  configFile: false,
  root,
  server: {
    host: '127.0.0.1',
    port: 5201,
    strictPort: false,
    watch: null,
    proxy: {
      '/linuxcnc-machine': {
        target: process.env.LINUXCNC_WASM_URL || 'https://localhost:5190',
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/linuxcnc-machine/, ''),
      },
    },
  },
})
await vite.listen()
const address = vite.httpServer?.address()
if (!address || typeof address === 'string') throw new Error('CAM machine harness server did not expose a port.')
const browser = await chromium.launch({ headless: true, executablePath: executable, args: ['--no-sandbox', '--disable-dev-shm-usage', '--enable-unsafe-swiftshader'] })
let report
try {
  const context = await browser.newContext({ ignoreHTTPSErrors: true })
  const page = await context.newPage()
  await page.goto(`http://127.0.0.1:${address.port}/chrome-cam-linuxcnc-machine-harness.html`, { waitUntil: 'domcontentloaded' })
  await page.waitForFunction(() => Boolean(window.__bitbybitCamLinuxcncMachineReport), null, { timeout: 240_000 })
  report = await page.evaluate(() => window.__bitbybitCamLinuxcncMachineReport)
  report = { ...report, browserId: 'chrome', browser: { product: await browser.version(), userAgent: await page.evaluate(() => navigator.userAgent) } }
  await context.close()
  if (report.status !== 'pass') process.exitCode = 1
} catch (error) {
  report = { schemaVersion: 1, status: 'failed', browserId: 'chrome', error: error instanceof Error ? error.stack || error.message : String(error) }
  process.exitCode = 1
} finally {
  await mkdir(resolve(root, 'config'), { recursive: true })
  await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`)
  console.log(JSON.stringify(report, null, 2))
  await browser.close()
  await vite.close()
}
