/**
 * SDK Test Runner — Domain: packages (v0.38.0)
 *
 * Tests package install validation for multi-file Starlark.
 * Requires admin role.
 */
(function () {
  'use strict';
  var T = window.SDKR;
  if (!T) return;

  // ── Minimal zip builder ──────────────────────────────────
  // Creates a valid zip archive in memory from an array of
  // {name: string, content: string} entries. No compression
  // (STORED method) — sufficient for small test payloads.

  function buildZip(entries) {
    var localHeaders = [];
    var centralHeaders = [];
    var offset = 0;

    entries.forEach(function (entry) {
      var nameBytes = new TextEncoder().encode(entry.name);
      var dataBytes = new TextEncoder().encode(entry.content);

      // Local file header (30 + name + data)
      var local = new Uint8Array(30 + nameBytes.length + dataBytes.length);
      var dv = new DataView(local.buffer);
      dv.setUint32(0, 0x04034b50, true);  // signature
      dv.setUint16(4, 20, true);           // version needed
      dv.setUint16(6, 0, true);            // flags
      dv.setUint16(8, 0, true);            // method: STORED
      dv.setUint16(10, 0, true);           // mod time
      dv.setUint16(12, 0, true);           // mod date
      dv.setUint32(14, crc32(dataBytes), true);
      dv.setUint32(18, dataBytes.length, true);  // compressed
      dv.setUint32(22, dataBytes.length, true);  // uncompressed
      dv.setUint16(26, nameBytes.length, true);
      dv.setUint16(28, 0, true);           // extra length
      local.set(nameBytes, 30);
      local.set(dataBytes, 30 + nameBytes.length);
      localHeaders.push(local);

      // Central directory header (46 + name)
      var central = new Uint8Array(46 + nameBytes.length);
      var cdv = new DataView(central.buffer);
      cdv.setUint32(0, 0x02014b50, true);  // signature
      cdv.setUint16(4, 20, true);           // version made by
      cdv.setUint16(6, 20, true);           // version needed
      cdv.setUint16(8, 0, true);            // flags
      cdv.setUint16(10, 0, true);           // method
      cdv.setUint16(12, 0, true);           // mod time
      cdv.setUint16(14, 0, true);           // mod date
      cdv.setUint32(16, crc32(dataBytes), true);
      cdv.setUint32(20, dataBytes.length, true);
      cdv.setUint32(24, dataBytes.length, true);
      cdv.setUint16(28, nameBytes.length, true);
      cdv.setUint16(30, 0, true);           // extra length
      cdv.setUint16(32, 0, true);           // comment length
      cdv.setUint16(34, 0, true);           // disk number
      cdv.setUint16(36, 0, true);           // internal attrs
      cdv.setUint32(38, 0, true);           // external attrs
      cdv.setUint32(42, offset, true);      // local header offset
      central.set(nameBytes, 46);
      centralHeaders.push(central);

      offset += local.length;
    });

    // End of central directory
    var centralSize = centralHeaders.reduce(function (sum, c) { return sum + c.length; }, 0);
    var eocd = new Uint8Array(22);
    var edv = new DataView(eocd.buffer);
    edv.setUint32(0, 0x06054b50, true);
    edv.setUint16(4, 0, true);
    edv.setUint16(6, 0, true);
    edv.setUint16(8, entries.length, true);
    edv.setUint16(10, entries.length, true);
    edv.setUint32(12, centralSize, true);
    edv.setUint32(16, offset, true);
    edv.setUint16(20, 0, true);

    var total = offset + centralSize + 22;
    var result = new Uint8Array(total);
    var pos = 0;
    localHeaders.forEach(function (h) { result.set(h, pos); pos += h.length; });
    centralHeaders.forEach(function (h) { result.set(h, pos); pos += h.length; });
    result.set(eocd, pos);

    return new Blob([result], { type: 'application/zip' });
  }

  // CRC-32 (IEEE)
  var crcTable = null;
  function crc32(bytes) {
    if (!crcTable) {
      crcTable = new Uint32Array(256);
      for (var n = 0; n < 256; n++) {
        var c = n;
        for (var k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
        crcTable[n] = c;
      }
    }
    var crc = 0xFFFFFFFF;
    for (var i = 0; i < bytes.length; i++) crc = crcTable[(crc ^ bytes[i]) & 0xFF] ^ (crc >>> 8);
    return (crc ^ 0xFFFFFFFF) >>> 0;
  }

  // ── Helpers ──────────────────────────────────────────────

  function makeManifest(overrides) {
    var base = {
      id: 'sdk-test-pkg-' + Date.now(),
      title: 'SDK Test Package',
      type: 'extension',
      tier: 'starlark',
      version: '0.0.1',
      tools: [{ name: 'noop', description: 'test', parameters: { type: 'object', properties: {} } }]
    };
    if (overrides) {
      Object.keys(overrides).forEach(function (k) { base[k] = overrides[k]; });
    }
    return base;
  }

  function makePkgFile(manifest, extraFiles) {
    var entries = [{ name: 'manifest.json', content: JSON.stringify(manifest) }];
    if (extraFiles) entries = entries.concat(extraFiles);
    var blob = buildZip(entries);
    return new File([blob], manifest.id + '.pkg', { type: 'application/zip' });
  }

  // ── Tests ────────────────────────────────────────────────

  T.registerDomain('packages', async function () {

    if (!window.sw || !sw.isAdmin) {
      await T.test('packages', 'guard', 'skip — not admin', async function () {
        T.assert(true, 'skipped (user is not admin)');
      });
      return;
    }

    // ── v0.38.0: Starlark entry point validation ──

    await T.test('packages', 'install-missing-star', 'install starlark pkg without script.star → 400', async function () {
      var manifest = makeManifest();
      var file = makePkgFile(manifest); // no script.star
      try {
        await sw.api.admin.packages.install(file);
        T.assert(false, 'should have rejected');
      } catch (e) {
        var msg = (e && e.message) || String(e);
        T.assert(
          msg.indexOf('400') >= 0 || msg.indexOf('missing entry point') >= 0 || msg.indexOf('error') >= 0,
          'expected 400 for missing entry point, got: ' + msg
        );
      }
    });

    await T.test('packages', 'install-with-star', 'install starlark pkg with script.star → 200', async function () {
      var manifest = makeManifest();
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'def on_tool_call(call):\n    return {"ok": True}\n' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id === manifest.id, 'expected install success with id');

      // Cleanup: delete the test package
      T.cleanup.push(async function () {
        try { await sw.api.admin.packages.del(manifest.id); } catch (_) {}
      });
    });

    await T.test('packages', 'install-with-submodules', 'install starlark pkg with star/ submodules → 200', async function () {
      var manifest = makeManifest();
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'load("star/helpers.star", "greet")\ndef on_tool_call(call):\n    return {"msg": greet()}\n' },
        { name: 'star/helpers.star', content: 'def greet():\n    return "hello"\n' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id === manifest.id, 'expected install success with id');

      // Cleanup
      T.cleanup.push(async function () {
        try { await sw.api.admin.packages.del(manifest.id); } catch (_) {}
      });
    });

    await T.test('packages', 'install-browser-tier', 'install browser-tier pkg without script.star → 200 (no validation)', async function () {
      var manifest = makeManifest({ tier: 'browser', type: 'surface', route: '/s/sdk-test-browser-' + Date.now() });
      // Remove tools — browser surfaces don't need them
      delete manifest.tools;
      var file = makePkgFile(manifest, [
        { name: 'js/main.js', content: '// noop' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id === manifest.id, 'browser tier should not require script.star');

      // Cleanup
      T.cleanup.push(async function () {
        try { await sw.api.admin.packages.del(manifest.id); } catch (_) {}
      });
    });

    await T.test('packages', 'install-custom-entry', 'install starlark pkg with custom entry_point → 200', async function () {
      var manifest = makeManifest({ entry_point: 'main.star' });
      var file = makePkgFile(manifest, [
        { name: 'main.star', content: 'def on_tool_call(call):\n    return {"ok": True}\n' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id === manifest.id, 'custom entry_point should work');

      // Cleanup
      T.cleanup.push(async function () {
        try { await sw.api.admin.packages.del(manifest.id); } catch (_) {}
      });
    });

    await T.test('packages', 'install-custom-entry-missing', 'install starlark pkg with missing custom entry_point → 400', async function () {
      var manifest = makeManifest({ entry_point: 'main.star' });
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'x = 1\n' } // wrong name
      ]);
      try {
        await sw.api.admin.packages.install(file);
        T.assert(false, 'should have rejected missing custom entry point');
      } catch (e) {
        var msg = (e && e.message) || String(e);
        T.assert(
          msg.indexOf('400') >= 0 || msg.indexOf('missing entry point') >= 0 || msg.indexOf('error') >= 0,
          'expected 400 for missing custom entry point'
        );
      }
    });

    // ── v0.38.2: Library package validation ──

    await T.test('packages', 'library-no-exports', 'library without exports → 400', async function () {
      var manifest = makeManifest({ type: 'library', tier: 'starlark' });
      delete manifest.tools;
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'x = 1\n' }
      ]);
      try {
        await sw.api.admin.packages.install(file);
        T.assert(false, 'should have rejected library without exports');
      } catch (e) {
        var msg = (e && e.message) || String(e);
        T.assert(
          msg.indexOf('400') >= 0 || msg.indexOf('exports') >= 0 || msg.indexOf('error') >= 0,
          'expected 400 for missing exports'
        );
      }
    });

    await T.test('packages', 'library-with-tools', 'library with tools → 400', async function () {
      var manifest = makeManifest({ type: 'library', tier: 'starlark', exports: ['fn1'] });
      // manifest already has tools from makeManifest
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'def fn1():\n    return 1\n' }
      ]);
      try {
        await sw.api.admin.packages.install(file);
        T.assert(false, 'should have rejected library with tools');
      } catch (e) {
        var msg = (e && e.message) || String(e);
        T.assert(
          msg.indexOf('400') >= 0 || msg.indexOf('tools') >= 0 || msg.indexOf('error') >= 0,
          'expected 400 for library with tools'
        );
      }
    });

    // ── v0.38.3: Config section manifest ──

    await T.test('packages', 'config-section-install', 'install pkg with config_section → manifest stored', async function () {
      var manifest = makeManifest({
        tier: 'browser',
        type: 'extension',
        config_section: {
          label: 'SDK Test Config',
          icon: 'M12 2L2 7',
          component: 'js/config.js',
          surfaces: ['admin', 'settings'],
          category: 'system'
        }
      });
      // Extension needs at least one of tools/pipes/hooks
      var file = makePkgFile(manifest, [
        { name: 'js/config.js', content: 'export default function() { return "config"; }' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id === manifest.id, 'expected install success');

      // Verify manifest roundtrip
      var pkg = await sw.api.admin.packages.get(manifest.id);
      T.assert(pkg && pkg.manifest, 'expected manifest in response');
      var cs = pkg.manifest.config_section;
      T.assert(cs && cs.label === 'SDK Test Config', 'expected config_section.label preserved');
      T.assert(cs.surfaces && cs.surfaces.length === 2, 'expected 2 surfaces');
      T.assert(cs.component === 'js/config.js', 'expected component preserved');

      // Cleanup
      T.cleanup.push(async function () {
        try { await sw.api.admin.packages.del(manifest.id); } catch (_) {}
      });
    });

    await T.test('packages', 'config-section-settings', 'config section settings round-trip', async function () {
      var manifest = makeManifest({
        tier: 'browser',
        type: 'extension',
        config_section: {
          label: 'SDK Config RT',
          component: 'js/config.js',
          surfaces: ['settings']
        }
      });
      var file = makePkgFile(manifest, [
        { name: 'js/config.js', content: 'export default function() { return "config"; }' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id, 'install success');

      // Write settings
      var settings = { api_key_label: 'My Service', timeout: 30 };
      await sw.api.admin.packages.updateSettings(manifest.id, settings);

      // Read back
      var stored = await sw.api.admin.packages.settings(manifest.id);
      T.assert(stored && stored.api_key_label === 'My Service', 'expected settings round-trip');
      T.assert(stored.timeout === 30, 'expected numeric setting preserved');

      // Cleanup
      T.cleanup.push(async function () {
        try { await sw.api.admin.packages.del(manifest.id); } catch (_) {}
      });
    });

    await T.test('packages', 'config-section-list', 'list packages → config_section visible', async function () {
      var manifest = makeManifest({
        tier: 'browser',
        type: 'extension',
        config_section: {
          label: 'SDK List Test',
          component: 'js/config.js',
          surfaces: ['admin']
        }
      });
      var file = makePkgFile(manifest, [
        { name: 'js/config.js', content: 'export default function() {}' }
      ]);
      await sw.api.admin.packages.install(file);

      var list = await sw.api.admin.packages.list();
      var found = (list || []).find(function (p) { return p.id === manifest.id; });
      T.assert(found, 'expected package in list');
      T.assert(found.manifest && found.manifest.config_section, 'expected config_section in list response');
      T.assert(found.manifest.config_section.label === 'SDK List Test', 'expected label match');

      // Cleanup
      T.cleanup.push(async function () {
        try { await sw.api.admin.packages.del(manifest.id); } catch (_) {}
      });
    });

    await T.test('packages', 'consumer-bad-dep', 'consumer with non-existent dependency → 400', async function () {
      var manifest = makeManifest({ dependencies: { 'nonexistent-lib-xyz': '>=1.0.0' } });
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'def on_tool_call(call):\n    return {"ok": True}\n' }
      ]);
      try {
        await sw.api.admin.packages.install(file);
        T.assert(false, 'should have rejected non-existent dependency');
      } catch (e) {
        var msg = (e && e.message) || String(e);
        T.assert(
          msg.indexOf('400') >= 0 || msg.indexOf('not found') >= 0 || msg.indexOf('error') >= 0,
          'expected 400 for non-existent dependency'
        );
      }
    });
  });
})();
