/**
 * SDK Test Runner — Domain: composition (v0.38.4)
 *
 * Tests the full library composition pattern:
 * library declares connection types → consumer depends on library →
 * connection created → types endpoint reflects it → cleanup.
 * Requires admin role.
 */
(function () {
  'use strict';
  var T = window.SDKR;
  if (!T) return;

  // ── Minimal zip builder (same as dependencies.js) ───────────
  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);
      var local = new Uint8Array(30 + nameBytes.length + dataBytes.length);
      var dv = new DataView(local.buffer);
      dv.setUint32(0, 0x04034b50, true);
      dv.setUint16(4, 20, true);
      dv.setUint16(8, 0, true);
      dv.setUint16(10, 0, true);
      dv.setUint16(12, 0, true);
      dv.setUint32(14, crc32(dataBytes), true);
      dv.setUint32(18, dataBytes.length, true);
      dv.setUint32(22, dataBytes.length, true);
      dv.setUint16(26, nameBytes.length, true);
      dv.setUint16(28, 0, true);
      local.set(nameBytes, 30);
      local.set(dataBytes, 30 + nameBytes.length);
      localHeaders.push(local);
      var central = new Uint8Array(46 + nameBytes.length);
      var cdv = new DataView(central.buffer);
      cdv.setUint32(0, 0x02014b50, true);
      cdv.setUint16(4, 20, true);
      cdv.setUint16(6, 20, true);
      cdv.setUint16(28, nameBytes.length, true);
      cdv.setUint32(16, crc32(dataBytes), true);
      cdv.setUint32(20, dataBytes.length, true);
      cdv.setUint32(24, dataBytes.length, true);
      cdv.setUint32(42, offset, true);
      central.set(nameBytes, 46);
      centralHeaders.push(central);
      offset += local.length;
    });
    var centralSize = centralHeaders.reduce(function (s, c) { return s + c.length; }, 0);
    var eocd = new Uint8Array(22);
    var edv = new DataView(eocd.buffer);
    edv.setUint32(0, 0x06054b50, true);
    edv.setUint16(8, entries.length, true);
    edv.setUint16(10, entries.length, true);
    edv.setUint32(12, centralSize, true);
    edv.setUint32(16, offset, true);
    var result = new Uint8Array(offset + centralSize + 22);
    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' });
  }

  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;
  }

  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('composition', async function () {

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

    var ts = Date.now();
    var libId = 'comp-test-lib-' + ts;
    var consumerId = 'comp-test-consumer-' + ts;
    var connType = 'comp-test-svc-' + ts;
    var connId = null;

    // ── 1. Install library with connection type ────────────

    await T.test('composition', 'install-library', 'install library with connection type declaration', async function () {
      var manifest = {
        id: libId,
        title: 'Composition Test Library',
        type: 'library',
        tier: 'starlark',
        version: '1.0.0',
        exports: ['get_data'],
        permissions: ['api.http', 'connections.read'],
        connections: [{
          type: connType,
          label: 'Test Service',
          fields: {
            base_url:  { type: 'url',    required: 'true',  label: 'Server URL' },
            api_token: { type: 'secret', required: 'true',  label: 'API Token' }
          },
          scopes: ['global', 'team', 'personal']
        }]
      };
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'def get_data():\n    return {"ok": True}\n' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id === libId, 'library should install');
      T.assert(r.type === 'library', 'type should be library');
    });

    T.cleanup.push(async function () {
      if (libId) try { await sw.api.admin.packages.del(libId); } catch (_) {}
    });

    // ── 2. Grant library permissions ────────────

    await T.test('composition', 'grant-permissions', 'grant library declared permissions', async function () {
      var r = await sw.api.post('/api/v1/admin/extensions/' + libId + '/permissions/grant-all', {});
      T.assert(true, 'permissions granted (or already granted)');
    });

    // ── 3. Connection type appears in discovery endpoint ────

    await T.test('composition', 'types-include-library', 'connection-types endpoint includes library type', async function () {
      var types = await sw.api.connectionTypes.list();
      T.assert(Array.isArray(types), 'should be array');
      var found = types.find(function (t) { return t.type === connType; });
      T.assert(found, 'library connection type should appear: ' + connType);
      T.assert(found.package_id === libId, 'package_id should be library');
      T.assert(found.label === 'Test Service', 'label should match');
      T.assert(found.fields && found.fields.api_token, 'should have api_token field');
      T.assert(found.fields.api_token.type === 'secret', 'api_token should be secret type');
    });

    // ── 4. Create connection of library's type ────────────

    await T.test('composition', 'create-connection', 'create connection of library connection type', async function () {
      var r = await sw.api.admin.connections.create({
        type: connType,
        package_id: libId,
        name: 'Comp Test Connection',
        config: { base_url: 'https://comp-test.example.com', api_token: 'test-token-12345' }
      });
      T.assert(r && r.id, 'should create connection');
      T.assert(r.type === connType, 'type should match');
      connId = r.id;
    });

    T.cleanup.push(async function () {
      if (connId) try { await sw.api.admin.connections.del(connId); } catch (_) {}
    });

    // ── 5. Install consumer with dependency on library ────

    await T.test('composition', 'install-consumer', 'install consumer depending on library', async function () {
      var manifest = {
        id: consumerId,
        title: 'Composition Test Consumer',
        type: 'extension',
        tier: 'starlark',
        version: '0.1.0',
        permissions: ['connections.read'],
        tools: [{ name: 'comp_noop', description: 'test tool', parameters: {} }],
        dependencies: {}
      };
      manifest.dependencies[libId] = '>=1.0.0';
      var file = makePkgFile(manifest, [
        { name: 'script.star', content: 'lib = lib.require("' + libId + '")\n\ndef on_tool_call(tool_name, params):\n    return lib.get_data()\n' }
      ]);
      var r = await sw.api.admin.packages.install(file);
      T.assert(r && r.id === consumerId, 'consumer should install');
    });

    T.cleanup.push(async function () {
      if (consumerId) try { await sw.api.admin.packages.del(consumerId); } catch (_) {}
    });

    // ── 6. Verify dependency recorded ────────────

    await T.test('composition', 'dependency-recorded', 'consumer depends on library', async function () {
      var r = await sw.api.admin.packages.dependencies(consumerId);
      T.assert(r && r.data, 'should return data');
      var dep = r.data.find(function (d) { return d.library_id === libId; });
      T.assert(dep, 'dependency on library should exist');
    });

    // ── 7. Cleanup: consumer, connection, library ────────────

    await T.test('composition', 'cleanup-consumer', 'uninstall consumer', async function () {
      await sw.api.admin.packages.del(consumerId);
      consumerId = null;
      T.assert(true, 'consumer uninstalled');
    });

    await T.test('composition', 'cleanup-connection', 'delete connection', async function () {
      await sw.api.admin.connections.del(connId);
      connId = null;
      T.assert(true, 'connection deleted');
    });

    await T.test('composition', 'cleanup-library', 'uninstall library', async function () {
      await sw.api.admin.packages.del(libId);
      libId = null;
      T.assert(true, 'library uninstalled');
    });

    // ── 8. Verify type removed after uninstall ────────────

    await T.test('composition', 'types-removed', 'connection type removed after library uninstall', async function () {
      var types = await sw.api.connectionTypes.list();
      var found = types.find(function (t) { return t.type === connType; });
      T.assert(!found, 'type should not appear after library uninstall');
    });

  });
})();
