import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { KiraClient, KiraConfigFlow, KiraIntegration, KiraMapper, createKiraDiscoveryDescriptor, kiraProfile, type IKiraSnapshot, type TKiraRawData } from '../../ts/integrations/kira/index.js';

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

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

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

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

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

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

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

tap.test('reads Kira Home Assistant code files as a native file snapshot', async () => {
  const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'kira-codes-'));
  const codesPath = path.join(tempDir, 'kira_codes.yaml');
  await fs.writeFile(codesPath, '- name: Power\n  code: ABC123\n  device: tv\n  type: raw\n  repeat: 2\n', 'utf8');

  try {
    const client = new KiraClient({ name: 'Kira Codes', codesPath });
    const snapshot = await client.getSnapshot(true);

    expect(snapshot.source).toEqual('client');
    expect(snapshot.entities.some((entityArg) => entityArg.id === 'power' && entityArg.platform === 'button')).toBeTrue();
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'code_count')?.state).toEqual(1);
    expect(snapshot.entities.find((entityArg) => entityArg.id === 'power')?.attributes?.code).toEqual('ABC123');
  } finally {
    await fs.rm(tempDir, { recursive: true, force: true });
  }
});

tap.test('exposes Kira runtime and unsupported control without executor', async () => {
  const integration = new KiraIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(kiraProfile.metadata.configFlow).toEqual(false);
  expect(kiraProfile.metadata.requirements).toEqual([
    "pykira==0.1.1",
  ]);

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

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

  const command = await runtime.callService!({ domain: "kira", service: kiraProfile.controlServices?.[0] || 'turn_on', target: {} });
  expect(command.success).toBeFalse();
  expect(command.error!).toContain('pykira over a UDP IR-IP bridge protocol');
  await runtime.destroy();
});

export default tap.start();
