const { _electron: electron } = require('playwright');
const fs = require('fs');
const path = require('path');

const projectRoot = path.resolve(__dirname, '..', '..');
const electronSourceExe = path.join(projectRoot, 'node_modules', 'electron', 'dist', 'electron.exe');
const electronExe = path.join(projectRoot, 'node_modules', 'electron', 'dist', 'OEMBatchBuilderTool.exe');
const mainScript = path.join(projectRoot, 'tools', 'oem-batch-builder', 'main.cjs');
const assetsDir = path.join(projectRoot, 'oem-assets');
const smokeUserDataDir = path.join(projectRoot, 'tools', 'oem-batch-builder', 'runs', 'ui-smoke-buildwin-user-data');

if (!fs.existsSync(electronExe) || fs.statSync(electronExe).mtimeMs < fs.statSync(electronSourceExe).mtimeMs) {
  fs.copyFileSync(electronSourceExe, electronExe);
}

function asset(name) {
  const filePath = path.join(assetsDir, name);
  if (!fs.existsSync(filePath)) throw new Error(`Missing test asset: ${filePath}`);
  return filePath;
}

(async () => {
  const app = await electron.launch({
    executablePath: electronExe,
    args: [`--user-data-dir=${smokeUserDataDir}`, mainScript],
    cwd: projectRoot,
    env: {
      ...process.env,
      ELECTRON_ENABLE_LOGGING: '1',
    },
  });

  const page = await app.firstWindow();
  await page.waitForSelector('#runBtn', { timeout: 15000 });

  const job = {
    id: `ui-buildwin-${Date.now()}`,
    enabled: true,
    brandName: 'UI BuildWin Test',
    brandSlogan: 'Smoke',
    brandShortName: 'UIBuildWinTest',
    brandDisplayName: 'UI BuildWin Test',
    apiBaseUrl: 'http://152.136.232.83:3002/api',
    version: '4.9.9',
    buildCommand: 'npm run build:win',
    assets: {
      qrcodePath: asset('qrcode.png'),
      logoPath: asset('logo.png'),
      iconPath: asset('icon.png'),
      loginBgPath: asset('login-bg.png'),
    },
    status: 'idle',
    message: '',
  };

  await page.evaluate((payload) => {
    localStorage.setItem('oem-batch-builder-jobs-v3', JSON.stringify([payload]));
    location.reload();
  }, job);

  await page.waitForSelector('#runBtn', { timeout: 15000 });
  await page.click('#runBtn');
  await page.waitForTimeout(60000);

  const processAlive = !app.process().killed;
  const windows = app.windows().filter(win => !win.isClosed());
  const statusText = await page.locator('.status').first().textContent().catch(() => '');
  const logText = await page.locator('#logBox').textContent().catch(() => '');

  console.log(JSON.stringify({
    processAlive,
    windowCount: windows.length,
    statusText,
    logTail: String(logText || '').slice(-1200),
  }, null, 2));

  if (!processAlive || windows.length === 0) {
    throw new Error('OEM build:win UI exited or window closed');
  }

  await app.close();
})();
