import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantOmbiIntegration, OmbiClient, OmbiConfigFlow, OmbiIntegration, OmbiMapper, createOmbiDiscoveryDescriptor, ombiProfile, type IOmbiSnapshot, type TOmbiRawData } from '../../ts/integrations/ombi/index.js';

const readBody = async (requestArg: IncomingMessage): Promise<string> => {
  const chunks: Buffer[] = [];
  for await (const chunk of requestArg) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  return Buffer.concat(chunks).toString('utf8');
};

const json = (responseArg: ServerResponse, valueArg: unknown, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'application/json');
  responseArg.end(JSON.stringify(valueArg));
};

const text = (responseArg: ServerResponse, valueArg: string, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'text/plain');
  responseArg.end(valueArg);
};

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

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

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

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

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

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

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

tap.test('exposes Ombi runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new OmbiIntegration();
  const alias = new HomeAssistantOmbiIntegration();
  expect(alias instanceof OmbiIntegration).toBeTrue();
  expect(alias.domain).toEqual("ombi");
  expect(integration.status).toEqual("control-runtime");
  expect(ombiProfile.metadata.configFlow).toEqual(false);
  expect(ombiProfile.metadata.requirements).toEqual([
    "pyombi==0.1.10",
  ]);

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

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

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

tap.test('reads and submits Ombi requests over the native HTTP API', async () => {
  const requests: Array<{ method?: string; url?: string; body?: string; apiKey?: string; userName?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    void (async () => {
      const body = requestArg.method === 'POST' ? await readBody(requestArg) : undefined;
      requests.push({ method: requestArg.method, url: requestArg.url, body, apiKey: requestArg.headers.apikey as string | undefined, userName: requestArg.headers.username as string | undefined });
      const url = new URL(requestArg.url || '/', 'http://127.0.0.1');

      if (requestArg.headers.apikey !== 'ombi-key' || requestArg.headers.username !== 'ombi-user') {
        json(responseArg, { error: 'unauthorized' }, 401);
        return;
      }
      if (url.pathname === '/ombi/api/v1/Status') {
        json(responseArg, { status: 'ok' });
        return;
      }
      if (url.pathname === '/ombi/api/v1/Request/movie/total') {
        text(responseArg, '3');
        return;
      }
      if (url.pathname === '/ombi/api/v1/Request/tv/total') {
        text(responseArg, '4');
        return;
      }
      if (url.pathname === '/ombi/api/v1/Request/music/total') {
        text(responseArg, '5');
        return;
      }
      if (url.pathname === '/ombi/api/v1/Request/count') {
        json(responseArg, { pending: 1, approved: 2, available: 3 });
        return;
      }
      if (url.pathname === '/ombi/api/v1/Search/movie/Arrival') {
        json(responseArg, [{ theMovieDbId: 42 }]);
        return;
      }
      if (url.pathname === '/ombi/api/v1/Search/tv/Fringe') {
        json(responseArg, [{ id: 99 }]);
        return;
      }
      if (url.pathname === '/ombi/api/v1/Search/music/album/Kind%20Of%20Blue') {
        json(responseArg, [{ foreignAlbumId: 'album-1' }]);
        return;
      }
      if (url.pathname === '/ombi/api/v1/Request/movie' || url.pathname === '/ombi/api/v1/Request/tv' || url.pathname === '/ombi/api/v1/Request/music') {
        json(responseArg, { isError: false });
        return;
      }
      json(responseArg, { error: 'not found', path: url.pathname }, 404);
    })().catch((errorArg) => {
      responseArg.statusCode = 500;
      responseArg.end(String(errorArg));
    });
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const url = `http://127.0.0.1:${port}/ombi`;
    const client = new OmbiClient({ url, username: 'ombi-user', apiKey: 'ombi-key', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const movie = await client.execute({ domain: 'ombi', service: 'submit_movie_request', target: {}, data: { name: 'Arrival' } });
    const tv = await client.execute({ domain: 'ombi', service: 'submit_tv_request', target: {}, data: { name: 'Fringe', season: 'latest' } });
    const music = await client.execute({ domain: 'ombi', service: 'submit_music_request', target: {}, data: { name: 'Kind Of Blue' } });
    const runtime = await new OmbiIntegration().setup({ url, username: 'ombi-user', apiKey: 'ombi-key', timeoutMs: 1000 }, {});
    const status = await runtime.callService!({ domain: 'ombi', service: 'status', target: {} });

    expect(snapshot.source).toEqual('http');
    expect(snapshot.online).toBeTrue();
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'movies')?.state).toEqual(3);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'pending')?.state).toEqual(1);
    expect(movie.success).toBeTrue();
    expect(tv.success).toBeTrue();
    expect(music.success).toBeTrue();
    expect(status.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/ombi/api/v1/Request/movie' && requestArg.body?.includes('theMovieDbId'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/ombi/api/v1/Request/tv' && requestArg.body?.includes('latestSeason'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/ombi/api/v1/Request/music' && requestArg.body?.includes('foreignAlbumId'))).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

export default tap.start();
