import test from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';

const root = fileURLToPath(new URL('../', import.meta.url));
const read = name => readFileSync(`${root}${name}`, 'utf8');

test('manifest exposes bundle, client, locale and icon entry points', () => {
  const manifest = JSON.parse(read('package.json'));
  assert.equal(manifest.name, '@local/dsh-pomodoro');
  assert.equal(manifest.type, 'module');
  assert.equal(manifest.dsh.bundle.patch, './cordis.patch.yml');
  assert.equal(manifest.dsh.client.platform, 'web');
  assert.equal(manifest.exports['./client'], './client.js');
  assert.equal(manifest.exports['./icon'], './icon.svg');
  assert.ok(manifest.files.includes('client.js'));
  assert.ok(manifest.files.includes('locale/*.json'));
});

test('patch inserts the matching package row', () => {
  const patch = read('cordis.patch.yml');
  assert.match(patch, /id: dsh-pomodoro/);
  assert.match(patch, /name: '@local\/dsh-pomodoro'/);
});

test('built client parses and registers the expected id', () => {
  const client = read('client.js');
  assert.match(client, /window\.__ModuleLoader__\.load/);
  assert.match(client, /id: '@local\/dsh-pomodoro'/);
  assert.doesNotMatch(client, /__CORE__|__UI__/);
  execFileSync(process.execPath, ['--check', `${root}client.js`], { stdio: 'pipe' });
});

test('icon is self-contained SVG artwork', () => {
  assert.ok(existsSync(`${root}icon.svg`));
  const icon = read('icon.svg');
  assert.match(icon, /^<svg[^>]*width="36"[^>]*height="36"/);
  assert.doesNotMatch(icon, /<script|<style|<text|<foreignObject|<image/i);
});

test('both locale files carry localized plugin metadata', () => {
  for (const [locale, title] of [['en', 'Pomodoro timer'], ['zh', '番茄钟']]) {
    const meta = JSON.parse(read(`locale/${locale}.json`)).meta;
    assert.equal(meta.title, title);
    assert.ok(meta.description.length > 80);
    assert.equal(meta.detail, undefined);
  }
});
