#!/usr/bin/env node
/** Generate an ASCII PLY cube (vertex colors) and load it via the drag&drop path
 *  in headless Chrome; screenshot to verify PLY support. */
import puppeteer from 'puppeteer-core';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';

const PLY = `ply
format ascii 1.0
element vertex 8
property float x
property float y
property float z
property uchar red
property uchar green
property uchar blue
element face 12
property list uchar int vertex_indices
end_header
-1 -1 -1 255 0 0
1 -1 -1 0 255 0
1 1 -1 0 0 255
-1 1 -1 255 255 0
-1 -1 1 255 0 255
1 -1 1 0 255 255
1 1 1 255 255 255
-1 1 1 90 90 90
3 0 1 2
3 0 2 3
3 4 5 6
3 4 6 7
3 0 4 7
3 0 7 3
3 1 5 6
3 1 6 2
3 3 2 6
3 3 6 7
3 0 1 5
3 0 5 4
`;
const dir = resolve('samples/plytest');
mkdirSync(dir, { recursive: true });
writeFileSync(resolve(dir, 'cube.ply'), PLY);
console.log('asset ->', resolve(dir, 'cube.ply'));

const url = process.argv.includes('--url') ? process.argv[process.argv.indexOf('--url') + 1] : 'http://localhost:3333';
const CHROME = ['C:/Program Files/Google/Chrome/Application/chrome.exe',
  'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'].find((p) => existsSync(p));
const browser = await puppeteer.launch({ executablePath: CHROME, headless: 'new',
  args: ['--no-sandbox', '--use-gl=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist', '--window-size=900,700'] });
const page = await browser.newPage();
await page.setViewport({ width: 900, height: 700 });
page.on('console', (m) => console.log('  [browser]', m.text()));
page.on('pageerror', (e) => console.log('  [pageerror]', e.message));
await page.evaluateOnNewDocument(() => { window.__r = null; addEventListener('hmw:ready', (e) => { window.__r = e.detail; }); });
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
await page.waitForSelector('#file-input');
await (await page.$('#file-input')).uploadFile(resolve(dir, 'cube.ply'));
await page.evaluate(() => document.getElementById('file-input').dispatchEvent(new Event('change', { bubbles: true })));
try { await page.waitForFunction('window.__r != null', { timeout: 30000, polling: 500 }); console.log('READY'); }
catch { console.log('TIMEOUT'); }
await new Promise((r) => setTimeout(r, 1200));
await page.screenshot({ path: resolve('ply-test.png') });
console.log('screenshot -> ply-test.png');
await browser.close();
