import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLidarrIntegration, LidarrClient, LidarrConfigFlow, LidarrIntegration, LidarrMapper, createLidarrDiscoveryDescriptor, lidarrProfile, type ILidarrSnapshot, type TLidarrRawData } from '../../ts/integrations/lidarr/index.js';

const rawData: TLidarrRawData = {
  device: {
    id: 'lidarr-device-1',
    name: "Lidarr Device",
    manufacturer: "Lidarr",
    model: "Lidarr local integration",
    serialNumber: 'lidarr-serial-1',
  },
  entities: [
    { id: 'status', name: 'Status', platform: "sensor", state: true, attributes: { domain: "lidarr" } },
  ],
  online: true,
  updatedAt: '2026-01-01T00:00:00.000Z',
  source: 'manual',
};

tap.test('matches manual Lidarr candidates and creates config flow output', async () => {
  const descriptor = createLidarrDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'lidarr-manual-match');
  const result = await matcher!.matches({ source: 'manual', id: 'lidarr-device-1', name: "Lidarr Device", metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual("lidarr");

  const validation = await descriptor.getValidators()[0].validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();

  const done = await (await new LidarrConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.uniqueId).toEqual('lidarr-device-1');
  expect(done.config?.rawData).toEqual(rawData);
});

tap.test('maps Lidarr raw snapshots to runtime devices and entities', async () => {
  const client = new LidarrClient({ name: "Lidarr Runtime", rawData });
  const snapshot = await client.getSnapshot();
  const mappedSnapshot = LidarrMapper.toSnapshotFromRaw({ name: "Lidarr Runtime" }, rawData);
  const devices = LidarrMapper.toDevices(mappedSnapshot);
  const entities = LidarrMapper.toEntities(mappedSnapshot);

  expect(snapshot.online).toBeTrue();
  expect(mappedSnapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual("lidarr");
  expect(devices[0].manufacturer).toEqual("Lidarr");
  expect(entities.some((entityArg) => entityArg.integrationDomain === "lidarr" && entityArg.platform === "sensor")).toBeTrue();
});

tap.test('fetches Lidarr HTTP API snapshots with API key headers', async () => {
  const originalFetch = globalThis.fetch;
  const requests: Array<{ url: string; apiKey?: string }> = [];
  globalThis.fetch = (async (inputArg: RequestInfo | URL, initArg?: RequestInit) => {
    const url = typeof inputArg === 'string' ? inputArg : inputArg instanceof URL ? inputArg.toString() : inputArg.url;
    const headers = new Headers(initArg?.headers);
    requests.push({ url, apiKey: headers.get('x-api-key') || undefined });
    const parsed = new URL(url);

    if (parsed.pathname === '/api/v1/system/status') {
      return jsonResponse({ appName: 'Lidarr', instanceName: 'Music Lidarr', version: '2.1.0', branch: 'main' });
    }
    if (parsed.pathname === '/api/v1/rootfolder') {
      return jsonResponse([{ path: '/srv/music', accessible: true, freeSpace: 10 * 1024 ** 3, totalSpace: 100 * 1024 ** 3 }]);
    }
    if (parsed.pathname === '/api/v1/queue') {
      return jsonResponse({ totalRecords: 1, records: [{ title: 'Queued Album', trackedDownloadState: 'downloading' }] });
    }
    if (parsed.pathname === '/api/v1/wanted/missing') {
      return jsonResponse({ totalRecords: 2, records: [{ title: 'Missing Album', artist: { artistName: 'Missing Artist' } }] });
    }
    if (parsed.pathname === '/api/v1/album') {
      return jsonResponse([{ title: 'One' }, { title: 'Two' }, { title: 'Three' }]);
    }
    return jsonResponse({ error: 'not found' }, 404);
  }) as typeof fetch;

  try {
    const client = new LidarrClient({ host: '127.0.0.1', port: 8686, apiKey: 'lidarr-key', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const runtime = await new LidarrIntegration().setup({ host: '127.0.0.1', port: 8686, apiKey: 'lidarr-key', timeoutMs: 1000 }, {});
    const entities = await runtime.entities();

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'version')?.state).toEqual('2.1.0');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'albums')?.state).toEqual(3);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'queue')?.state).toEqual(1);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'wanted')?.state).toEqual(2);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'disk_space_music')?.state).toEqual(10);
    expect(entities.some((entityArg) => entityArg.id === 'sensor.music_lidarr_albums')).toBeTrue();
    expect(requests.every((requestArg) => requestArg.apiKey === 'lidarr-key')).toBeTrue();
    expect(requests.some((requestArg) => {
      const url = new URL(requestArg.url);
      return url.pathname === '/api/v1/queue' && url.searchParams.get('pageSize') === '20';
    })).toBeTrue();
    expect(requests.some((requestArg) => new URL(requestArg.url).pathname === '/api/v1/wanted/missing')).toBeTrue();
    await runtime.destroy();
  } finally {
    globalThis.fetch = originalFetch;
  }
});

tap.test('exposes Lidarr runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LidarrIntegration();
  const alias = new HomeAssistantLidarrIntegration();
  expect(alias instanceof LidarrIntegration).toBeTrue();
  expect(alias.domain).toEqual("lidarr");
  expect(integration.status).toEqual("read-only-runtime");
  expect(lidarrProfile.metadata.configFlow).toEqual(true);
  expect(lidarrProfile.metadata.requirements).toEqual([
    "aiopyarr==23.4.0",
  ]);

  const runtime = await integration.setup({ name: "Lidarr Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "lidarr", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "lidarr", service: 'refresh', target: {} });
  const snapshot = statusResult.data as ILidarrSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual("Lidarr Device");

  const command = await runtime.callService!({ domain: "lidarr", service: lidarrProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('requires an injected client.execute() or commandExecutor');
  await runtime.destroy();
});

export default tap.start();

const jsonResponse = (valueArg: unknown, statusArg = 200): Response => {
  return new Response(JSON.stringify(valueArg), {
    status: statusArg,
    headers: { 'content-type': 'application/json' },
  });
};
