import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantPlugwiseIntegration, PlugwiseClient, PlugwiseConfigFlow, PlugwiseIntegration, PlugwiseMapper, createPlugwiseDiscoveryDescriptor, plugwiseProfile, type IPlugwiseSnapshot, type TPlugwiseRawData } from '../../ts/integrations/plugwise/index.js';

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

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

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

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

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

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

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

tap.test('polls Plugwise Smile domain_objects through native HTTP', async () => {
  const originalFetch = globalThis.fetch;
  const requests: Array<{ url: string; authorization?: string }> = [];
  globalThis.fetch = (async (inputArg: Parameters<typeof fetch>[0], initArg?: Parameters<typeof fetch>[1]) => {
    const headers = initArg?.headers as Record<string, string> | undefined;
    requests.push({ url: String(inputArg), authorization: headers?.authorization });
    const xml = `
      <domain_objects>
        <gateway>
          <firmware_version>4.0.1</firmware_version>
          <hardware_version>1.0</hardware_version>
          <hostname>smile-host</hostname>
          <mac_address>00:11:22:33:44:55</mac_address>
          <vendor_model>smile_open_therm</vendor_model>
        </gateway>
        <appliance id="gateway-1">
          <name>Adam</name>
          <type>gateway</type>
          <logs>
            <point_log>
              <measurement id="temperature-1">
                <type>temperature</type>
                <unit>C</unit>
                <value>20.5</value>
              </measurement>
            </point_log>
          </logs>
        </appliance>
      </domain_objects>`;
    return new Response(xml, { status: 200, headers: { 'content-type': 'application/xml' } });
  }) as typeof fetch;

  try {
    const client = new PlugwiseClient({ host: 'plugwise.local', password: 'secret', timeoutMs: 500 });
    const snapshot = await client.getSnapshot(true);
    const entity = snapshot.entities.find((entityArg) => entityArg.id === 'gateway_1_temperature');

    expect(requests[0].url).toEqual('http://plugwise.local/core/domain_objects');
    expect(requests[0].authorization).toEqual(`Basic ${Buffer.from('smile:secret').toString('base64')}`);
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.name).toEqual('Adam');
    expect(snapshot.device.model).toEqual('smile_open_therm');
    expect(entity?.state).toEqual(20.5);
    expect(entity?.unit).toEqual('C');
  } finally {
    globalThis.fetch = originalFetch;
  }
});

tap.test('exposes Plugwise runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new PlugwiseIntegration();
  const alias = new HomeAssistantPlugwiseIntegration();
  expect(alias instanceof PlugwiseIntegration).toBeTrue();
  expect(alias.domain).toEqual("plugwise");
  expect(integration.status).toEqual("read-only-runtime");
  expect(plugwiseProfile.metadata.configFlow).toEqual(true);
  expect(plugwiseProfile.metadata.requirements).toEqual([
    "plugwise==1.11.3",
  ]);

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

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

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