import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { randomUUID, createHash } from 'node:crypto';
import { _electron, expect } from 'playwright/test';
import { createRequestHandler, createSessionPublisher } from '../src/server/app.mjs';
import { hostAuthority } from '../src/core/desktop/host-authority.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';

const hash = bytes => createHash('sha256').update(bytes).digest('hex');
export async function desktopProjectQa({ store, provider, runtime, sample, kind }) {
  const appRoot = path.resolve(process.env.AGENT_WORKBENCH_DESKTOP_QA_APP_ROOT || process.cwd()), server = http.createServer(), clients = new Set(), token = randomUUID();
  runtime.appDirectory = appRoot; store.claimRuntime(); store.on('update', createSessionPublisher(clients));
  server.on('request', createRequestHandler({ appDirectory: appRoot, server, store, provider, runtime, token, clients, started: Date.now(), getPort: () => server.address().port, shutdown: () => {} }));
  await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  const authority = hostAuthority({ appDirectory: appRoot, server, store, provider, runtime }); authority.initialize();
  let application, page, selected; const events = [], errors = [], screenshots = [];
  async function launch() {
    const executable = desktopExecutableIdentity(appRoot).path, packaged = executable.toLowerCase().endsWith('agentworkbench.exe');
    application = await _electron.launch({ executablePath: executable,
      args: [...(packaged ? [] : [path.join(appRoot, 'dist-desktop/main.cjs')]), '--app-root', appRoot, '--data-root', store.directory, '--node', process.execPath, '--port', String(server.address().port), '--hidden-window'],
      cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
    page = await application.firstWindow(); page.on('pageerror', error => errors.push(error.message));
    await page.locator('.connection.connected').waitFor({ timeout: 30000 });
    if (selected) await select(selected);
  }
  async function select(session) {
    selected = session;
    const project = page.getByRole('combobox', { name: '当前项目', exact: true });
    if (!await project.isVisible()) await page.getByRole('button', { name: '展开项目栏', exact: true }).click();
    await project.selectOption(session.projectId);
    await expect.poll(() => page.evaluate(() => localStorage.getItem('awb-session')), { timeout: 20000 }).toBe(session.id);
  }
  async function closeInspector() { const close = page.getByRole('button', { name: '关闭检视区', exact: true }); if (await close.isVisible().catch(() => false)) await close.click(); }
  async function review(session, ids) {
    await select(session); await closeInspector();
    const prepared = [...store.core.change_set.values()].find(value => value.sessionId === session.id && value.status === 'prepared' && JSON.stringify(value.files.map(file => file.changeId).sort()) === JSON.stringify(ids.slice().sort()));
    if (prepared) {
      await page.getByRole('button', { name: '隔离协作', exact: true }).click();
      await page.getByRole('button', { name: '打开父工程变更集审查', exact: true }).click();
      await page.getByRole('button', { name: '审查变更集', exact: true }).click();
    } else {
      if (await page.getByRole('button', { name: '查看改动', exact: true }).isVisible()) await page.getByRole('button', { name: '查看改动', exact: true }).click();
      else await page.locator('.inspector-tabs').getByRole('button', { name: /^改动/ }).click();
      await page.getByRole('button', { name: '组合审查', exact: true }).click();
      await page.getByRole('dialog', { name: '选择要一起审查的提案', exact: true }).getByRole('button', { name: '封存审查范围', exact: true }).click();
    }
    const dialog = page.getByRole('dialog', { name: '多文件变更集审查', exact: true });
    const confirm = dialog.getByRole('button', { name: '确认应用全部 ' + ids.length + ' 项', exact: true }); await confirm.waitFor();
    const matching = [...store.core.change_set.values()].filter(value => value.sessionId === session.id && value.status !== 'completed' && JSON.stringify(value.files.map(file => file.changeId).sort()) === JSON.stringify(ids.slice().sort()));
    assert.equal(matching.length, 1); const set = matching[0];
    const response = page.waitForResponse(value => new URL(value.url()).pathname === '/api/sessions/' + session.id + '/change-sets/' + set.id + '/apply'
      && value.request().method() === 'POST', { timeout: 120000 });
    await confirm.click(); const applied = await response;
    assert.equal(applied.status(), 202, 'Original desktop apply request was rejected');
    const operation = runtime.changeSetManager().active.get(set.id);
    if (operation) await operation.promise;
    assert.equal(set.status, 'completed', JSON.stringify({ status: set.status, summary: set.summary, requiresVerification: set.requiresVerification }));
    await expect(dialog).toContainText('全部应用完成', { timeout: 20000 }); await page.keyboard.press('Escape');
    assert.equal(set.status, 'completed'); events.push({ action: 'actual-desktop-file-review', taskId: session.taskId, changeSetId: set.id, fingerprint: set.fingerprint, paths: set.files.map(value => value.path) }); return set;
  }
  async function approve(session, approval) {
    await select(session); await closeInspector();
    const button = page.getByRole('button', { name: '确认执行', exact: true }); await button.waitFor({ timeout: 20000 });
    assert.equal(session.approvals.filter(value => value.status === 'pending').length, 1); assert.equal(session.approvals.find(value => value.status === 'pending').id, approval.id);
    await button.click(); await expect.poll(() => approval.status).toBe('approved'); events.push({ action: 'actual-desktop-original-approval', approvalId: approval.id, taskId: session.taskId });
  }
  async function cycle(session, label) {
    await select(session); const identity = authority.identity(), eventSeq = session.eventSeq, taskId = session.taskId, runId = session.runId;
    const originalEvents = () => {
      const events = []; let cursor = 0;
      while (cursor < eventSeq) {
        const chunk = store.eventsAfter(cursor, { sessionId: session.id, limit: 500 });
        events.push(...chunk.events.filter(value => value.seq <= eventSeq));
        if (!chunk.hasMore || chunk.nextCursor >= eventSeq) break;
        assert.ok(chunk.nextCursor > cursor); cursor = chunk.nextCursor;
      }
      return events;
    };
    const retainedEvents = originalEvents(); assert.equal(retainedEvents.at(-1).seq, eventSeq);
    const completed = () => [...store.core.tool.values()].filter(value => value.sessionId === session.id && value.state === 'completed');
    const prior = hash(Buffer.from(JSON.stringify(completed()))), approvals = session.approvals.map(value => ({ id: value.id, status: value.status }));
    await application.close(); application = null;
    assert.equal(runtime.isActive(session.id), true); assert.equal(authority.identity().instanceId, identity.instanceId); assert.equal(process.pid, identity.pid);
    await launch(); assert.equal(session.taskId, taskId); assert.equal(session.runId, runId); assert.ok(session.eventSeq >= eventSeq); assert.deepEqual(originalEvents(), retainedEvents);
    const replay = await page.evaluate(async ({ sessionId, cursor }) => {
      const bootstrap = await (await fetch('/api/bootstrap')).json();
      const response = await fetch('/api/events/history?session=' + encodeURIComponent(sessionId) + '&after=' + cursor + '&limit=500', { headers: { 'x-workbench-token': bootstrap.token } });
      if (!response.ok) throw Error('Original desktop event replay failed (' + response.status + ')'); return response.json();
    }, { sessionId: session.id, cursor: eventSeq - 1 });
    assert.deepEqual(replay.events[0], retainedEvents.at(-1)); assert.ok(replay.events.every((value, index) => !index || value.seq > replay.events[index - 1].seq));
    assert.equal(hash(Buffer.from(JSON.stringify(completed()))), prior); assert.deepEqual(session.approvals.map(value => ({ id: value.id, status: value.status })), approvals);
    events.push({ action: label, hostPid: process.pid, taskId, runId, eventSeq, reopenedEventSeq: session.eventSeq, replayCursor: replay.nextCursor,
      retainedEvents: retainedEvents.length, retainedEventsSha256: hash(Buffer.from(JSON.stringify(retainedEvents))), instanceId: identity.instanceId, completedToolSha256: prior, approvals });
  }
  async function capture(session, label) {
    await select(session); await closeInspector(); await page.getByRole('button', { name: '隔离协作', exact: true }).click();
    for (const width of [1440, 390]) {
      const native = await application.browserWindow(page); await native.evaluate((value, width) => { value.showInactive(); value.setContentSize(width, 900); }, width);
      await expect.poll(() => page.evaluate(() => innerWidth)).toBe(width);
      const filename = path.join(sample, kind + '-' + label + '-' + width + '.png'); await page.screenshot({ path: filename }); fs.writeFileSync(filename + '.html', await page.content());
      assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); screenshots.push({ file: filename, width, sha256: hash(fs.readFileSync(filename)) });
    }
    await (await application.browserWindow(page)).evaluate(value => value.setContentSize(1440, 1000));
    // Electron resize and React's responsive state settle independently.
    // Await both before querying a control whose accessible name changes.
    await expect.poll(() => page.evaluate(() => innerWidth)).toBe(1440);
    await expect(page.getByRole('button', { name: '关闭检视区', exact: true })).toBeHidden();
    await page.keyboard.press('Escape'); await expect(page.getByRole('dialog', { name: '隔离协作', exact: true })).toBeHidden();
    await closeInspector();
  }
  await launch();
  return { select, review, approve, cycle, capture, events, screenshots, errors, get page() { return page; },
    async resize(width, height) { await (await application.browserWindow(page)).evaluate((value, size) => { value.showInactive(); value.setContentSize(size.width, size.height); }, { width, height }); await expect.poll(() => page.evaluate(() => innerWidth)).toBe(width); },
    async download(filename, trigger) {
      const id = randomUUID();
      await application.evaluate(({ session }, { id, filename }) => {
        globalThis.workbenchQaDownloads ??= {};
        globalThis.workbenchQaDownloads[id] = { state: 'waiting' };
        session.defaultSession.once('will-download', (_event, item) => {
          const value = globalThis.workbenchQaDownloads[id]; value.suggestedFilename = item.getFilename(); value.state = 'started';
          item.setSavePath(filename); // Actual Electron DownloadItem; only the owned destination selection is a QA fixture.
          item.once('done', (_event, state) => { value.state = state; value.bytes = item.getReceivedBytes(); value.totalBytes = item.getTotalBytes(); });
        });
      }, { id, filename });
      await trigger(); await expect.poll(() => application.evaluate((_electron, id) => globalThis.workbenchQaDownloads[id].state, id), { timeout: 30000 }).toBe('completed');
      const value = await application.evaluate((_electron, id) => globalThis.workbenchQaDownloads[id], id);
      assert.equal(value.bytes, value.totalBytes); assert.equal(fs.statSync(filename).size, value.bytes);
      events.push({ action: 'actual-electron-native-download', ...value, file: filename, sha256: hash(fs.readFileSync(filename)), scope: 'Actual DownloadItem and transferred bytes; own output path chosen by QA without exercising the Windows save dialog.' });
      return value;
    },
    scope: 'Real Electron renderer and fixed native main/preload; own in-process Node fixture host, actual native Harness/HTTP/check/Git. The whole fixture host is never exited from its desktop UI.',
    async failure(error) { if (!page || page.isClosed()) return; const filename = path.join(sample, kind + '-desktop-failure'); fs.writeFileSync(filename + '.html', await page.content()); fs.writeFileSync(filename + '.json', JSON.stringify({ error: error.stack, dialogs: await page.getByRole('dialog').allTextContents(), errors, events }, null, 2)); await (await application.browserWindow(page)).evaluate(value => value.showInactive()); await page.screenshot({ path: filename + '.png' }); },
    async close() { await application?.close(); for (const response of clients) response.destroy(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); assert.deepEqual(errors, []); } };
}
