import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import test from 'node:test';

const root = join(import.meta.dirname, '..', '..', '..');

async function manifest(target: 'firefox' | 'chromium'): Promise<Record<string, any>> {
  return JSON.parse(await readFile(join(root, 'dist', target, 'manifest.json'), 'utf8')) as Record<string, any>;
}

test('Firefox manifest is MV3 with narrow ChatGPT host access and background script', async () => {
  const value = await manifest('firefox');
  assert.equal(value.manifest_version, 3);
  assert.deepEqual(value.host_permissions, ['https://chatgpt.com/*']);
  assert.deepEqual(value.permissions, ['storage', 'tabs', 'alarms']);
  assert.deepEqual(value.background, { scripts: ['background.js'] });
  assert.deepEqual(value.action, { default_popup: 'popup.html', default_title: 'Execution Continuity' });
  assert.equal(value.browser_specific_settings.gecko.id, 'chatgpt-orchestrator@alexcodeplace');
  assert.equal(value.browser_specific_settings.gecko.strict_min_version, '142.0');
  assert.deepEqual(value.browser_specific_settings.gecko.data_collection_permissions.required, ['browsingActivity']);
});

test('Chromium manifest is MV3 with service worker and loopback onboarding hosts', async () => {
  const value = await manifest('chromium');
  assert.equal(value.manifest_version, 3);
  assert.deepEqual(value.host_permissions, ['https://chatgpt.com/*', 'http://127.0.0.1/*', 'http://localhost/*']);
  assert.deepEqual(value.background, { service_worker: 'background.js' });
  assert.deepEqual(value.action, { default_popup: 'popup.html', default_title: 'Execution Continuity' });
  assert.equal(value.browser_specific_settings, undefined);
});

test('built extension contains no private ChatGPT backend endpoint seam', async () => {
  for (const target of ['firefox', 'chromium'] as const) {
    for (const file of ['background.js', 'content.js', 'popup.js', 'dashboard.js']) {
      const text = await readFile(join(root, 'dist', target, file), 'utf8');
      assert.doesNotMatch(text, /backend-api|\/api\/conversation|remote-debugging|playwright|selenium/i);
    }
  }
});


test('built extension packages the C9-C11 operator surfaces', async () => {
  for (const target of ['firefox', 'chromium'] as const) {
    const popup = await readFile(join(root, 'dist', target, 'popup.html'), 'utf8');
    const dashboard = await readFile(join(root, 'dist', target, 'dashboard.html'), 'utf8');
    const options = await readFile(join(root, 'dist', target, 'options.html'), 'utf8');
    assert.match(popup, /Open dashboard/);
    assert.match(dashboard, /Execution Continuity Dashboard/);
    assert.match(options, /Settings \/ Advanced/);
  }
});
