#!/usr/bin/env node
/**
 * Generate a textured cube (cube.obj + cube.mtl + checker.png), then load it
 * through the real drag&drop path (uploadFile of all 3) in headless Chrome and
 * screenshot — verifies OBJ texture support (map_Kd → dropped image blob URL).
 *
 * USAGE: node tools/tex-test.mjs [--url http://localhost:3333]
 */
import puppeteer from 'puppeteer-core';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { deflateSync } from 'node:zlib';
import { resolve } from 'node:path';

// ---- minimal PNG encoder (truecolor RGB, filter 0) ----
const CRC = (() => {
  const t = new Uint32Array(256);
  for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; }
  return (buf) => { let c = 0xffffffff; for (let i = 0; i < buf.length; i++) c = t[(c ^ buf[i]) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
})();
function chunk(type, data) {
  const len = Buffer.alloc(4); len.writeUInt32BE(data.length, 0);
  const td = Buffer.concat([Buffer.from(type, 'ascii'), data]);
  const crc = Buffer.alloc(4); crc.writeUInt32BE(CRC(td), 0);
  return Buffer.concat([len, td, crc]);
}
function checkerPng(size = 64, cell = 8) {
  const raw = Buffer.alloc((size * 3 + 1) * size);
  for (let y = 0; y < size; y++) {
    let o = y * (size * 3 + 1); raw[o++] = 0; // filter byte
    for (let x = 0; x < size; x++) {
      const on = ((x / cell | 0) + (y / cell | 0)) & 1;
      raw[o++] = on ? 255 : 0; raw[o++] = on ? 0 : 255; raw[o++] = 255; // magenta / cyan
    }
  }
  const ihdr = Buffer.alloc(13);
  ihdr.writeUInt32BE(size, 0); ihdr.writeUInt32BE(size, 4);
  ihdr[8] = 8; ihdr[9] = 2; // bitdepth 8, colortype 2 (RGB)
  const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
  return Buffer.concat([sig, chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
}

const OBJ = `mtllib cube.mtl
v -1 -1 -1
v 1 -1 -1
v 1 1 -1
v -1 1 -1
v -1 -1 1
v 1 -1 1
v 1 1 1
v -1 1 1
vt 0 0
vt 1 0
vt 1 1
vt 0 1
usemtl checker
f 1/1 2/2 3/3
f 1/1 3/3 4/4
f 5/1 6/2 7/3
f 5/1 7/3 8/4
f 1/1 5/2 8/3
f 1/1 8/3 4/4
f 2/1 6/2 7/3
f 2/1 7/3 3/4
f 4/1 3/2 7/3
f 4/1 7/3 8/4
f 1/1 2/2 6/3
f 1/1 6/3 5/4
`;
const MTL = `newmtl checker
Kd 1 1 1
map_Kd checker.png
`;

const dir = resolve('samples/textest');
mkdirSync(dir, { recursive: true });
writeFileSync(resolve(dir, 'cube.obj'), OBJ);
writeFileSync(resolve(dir, 'cube.mtl'), MTL);
writeFileSync(resolve(dir, 'checker.png'), checkerPng());
console.log('assets ->', dir);

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');
const input = await page.$('#file-input');
await input.uploadFile(resolve(dir, 'cube.obj'), resolve(dir, 'cube.mtl'), resolve(dir, 'checker.png'));
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, 1500));
await page.screenshot({ path: resolve('tex-test.png') });
console.log('screenshot -> tex-test.png');
await browser.close();
