import { createServer } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantObihaiIntegration, ObihaiClient, ObihaiConfigFlow, ObihaiIntegration, ObihaiMapper, createObihaiDiscoveryDescriptor, obihaiProfile, type IObihaiSnapshot, type TObihaiRawData } from '../../ts/integrations/obihai/index.js';

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

tap.test('reads and reboots Obihai over local HTTP Digest pages', async () => {
  const requests: Array<{ url?: string; authorization?: string }> = [];
  const server = createServer((requestArg, responseArg) => {
    requests.push({ url: requestArg.url, authorization: requestArg.headers.authorization });
    if (!requestArg.headers.authorization) {
      responseArg.statusCode = 401;
      responseArg.setHeader('www-authenticate', 'Digest realm="Obihai", nonce="abc123", qop="auth"');
      responseArg.end('auth required');
      return;
    }
    expect(requestArg.headers.authorization).toContain('Digest username="admin"');
    const path = new URL(requestArg.url || '/', 'http://127.0.0.1').pathname;
    responseArg.setHeader('content-type', path.endsWith('.xml') ? 'application/xml' : 'text/html');
    if (path === '/DI_S_.xml') {
      responseArg.end('<root><model reboot_req="false"/><object name="Product Information"><parameter name="ModelName"><value current="OBi200"/></parameter><parameter name="HardwareVersion"><value current="1.4"/></parameter><parameter name="SoftwareVersion"><value current="3.2.2"/></parameter><parameter name="SerialNumber"><value current="OBI123"/></parameter><parameter name="UpTime"><value current="1 days 02:03:04"/></parameter></object><object name="WAN Status"><parameter name="MACAddress"><value current="9C:AD:EF:00:11:22"/></parameter></object><object name="SP1 Service Status"><parameter name="Status"><value current="Registered"/></parameter><parameter name="CallState"><value current="Idle"/></parameter></object></root>');
      return;
    }
    if (path === '/PI_FXS_1_Stats.xml') {
      responseArg.end('<root><object name="Port Status" subtitle="Phone 1 Port"><parameter name="State"><value current="On Hook"/></parameter><parameter name="LastCallerInfo"><value current="\'Alice\'"/></parameter></object></root>');
      return;
    }
    if (path === '/callstatus.htm') {
      responseArg.end('<tr>Number of Active Calls: 1</tr><td>Inbound</td>');
      return;
    }
    if (path === '/rebootgetconfig.htm') {
      responseArg.end('rebooting');
      return;
    }
    responseArg.statusCode = 404;
    responseArg.end('not found');
  });

  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 client = new ObihaiClient({ host: '127.0.0.1', port, username: 'admin', password: 'secret', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot();
    const reboot = await client.execute({ domain: 'obihai', service: 'press', target: { entityId: 'button.obihai_reboot' } });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.serialNumber).toEqual('OBI123');
    expect(snapshot.device.attributes?.macAddress).toEqual('9C:AD:EF:00:11:22');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'call_direction')?.state).toEqual('Inbound Call');
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'phone_1_port')?.state).toEqual('On Hook');
    expect(reboot.success).toBeTrue();
    expect(requests.some((requestArg) => requestArg.url === '/rebootgetconfig.htm' && requestArg.authorization?.startsWith('Digest '))).toBeTrue();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

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

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

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

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

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

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

tap.test('exposes Obihai runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new ObihaiIntegration();
  const alias = new HomeAssistantObihaiIntegration();
  expect(alias instanceof ObihaiIntegration).toBeTrue();
  expect(alias.domain).toEqual("obihai");
  expect(integration.status).toEqual("control-runtime");
  expect(obihaiProfile.metadata.configFlow).toEqual(true);
  expect(obihaiProfile.metadata.requirements).toEqual([
    "pyobihai==1.4.2",
  ]);

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

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

  const command = await runtime.callService!({ domain: "obihai", service: obihaiProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('Static snapshots/manual data are read-only');
  await runtime.destroy();
});

export default tap.start();
