import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLgNetcastIntegration, LgNetcastClient, LgNetcastConfigFlow, LgNetcastIntegration, LgNetcastMapper, createLgNetcastDiscoveryDescriptor, lgNetcastProfile, type ILgNetcastSnapshot, type TLgNetcastRawData } from '../../ts/integrations/lg_netcast/index.js';

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

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

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

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

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

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

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

tap.test('polls and controls LG Netcast through native ROAP HTTP', async () => {
  const originalFetch = globalThis.fetch;
  const requests: Array<{ url: string; method?: string; body?: string }> = [];

  globalThis.fetch = (async (inputArg: RequestInfo | URL, initArg?: RequestInit) => {
    const url = String(inputArg);
    const body = typeof initArg?.body === 'string' ? initArg.body : undefined;
    requests.push({ url, method: initArg?.method, body });

    if (url.includes('/data?target=rootservice.xml')) {
      return new Response('<root><device><uuid>netcast-uuid</uuid><modelName>47LM760S</modelName><friendlyName>Living TV</friendlyName></device></root>');
    }
    if (url.includes('/data?target=volume_info')) {
      return new Response('<root><data><level>22</level><mute>false</mute></data></root>');
    }
    if (url.includes('/data?target=cur_channel')) {
      return new Response('<root><data><major>7</major><chname>HDMI 1</chname><progName>Movie</progName></data></root>');
    }
    if (url.endsWith('/auth')) {
      return new Response('<envelope><session>session-1</session></envelope>');
    }
    if (url.endsWith('/command')) {
      return new Response('<ok />');
    }
    return new Response('not found', { status: 404 });
  }) as typeof globalThis.fetch;

  try {
    const client = new LgNetcastClient({ host: '192.0.2.10', accessToken: '123456' });
    const snapshot = await client.getSnapshot(true);
    const entity = snapshot.entities.find((entityArg) => entityArg.id === 'media_player');

    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('netcast-uuid');
    expect(entity?.attributes?.volumeLevel).toEqual(0.22);
    expect(entity?.attributes?.channelName).toEqual('HDMI 1');

    const result = await client.execute({ domain: 'media_player', service: 'media_pause', target: {} });
    expect(result.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.body?.includes('<type>AuthReq</type><value>123456</value>'))).toBeTrue();
    expect(requests.some((requestArg) => requestArg.body?.includes('<type>HandleKeyInput</type><value>34</value>'))).toBeTrue();
  } finally {
    globalThis.fetch = originalFetch;
  }
});

tap.test('exposes LG Netcast runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LgNetcastIntegration();
  const alias = new HomeAssistantLgNetcastIntegration();
  expect(alias instanceof LgNetcastIntegration).toBeTrue();
  expect(alias.domain).toEqual("lg_netcast");
  expect(integration.status).toEqual("control-runtime");
  expect(lgNetcastProfile.metadata.configFlow).toEqual(true);
  expect(lgNetcastProfile.metadata.requirements).toEqual([
    "pylgnetcast==0.3.9",
  ]);

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

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

  const command = await runtime.callService!({ domain: "lg_netcast", service: lgNetcastProfile.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();
