import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomeAssistantLocalTodoIntegration, LocalTodoClient, LocalTodoConfigFlow, LocalTodoIntegration, LocalTodoMapper, createLocalTodoDiscoveryDescriptor, localTodoProfile, type ILocalTodoSnapshot, type TLocalTodoRawData } from '../../ts/integrations/local_todo/index.js';

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

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

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

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

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

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

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

tap.test('reads Home Assistant Local To-do ICS storage files', async () => {
  const client = new LocalTodoClient({ name: 'House Tasks', filePath: 'test/local_todo/sample.ics' });
  const snapshot = await client.getSnapshot(true);
  const items = snapshot.entities.find((entityArg) => entityArg.id === 'todo_items');
  const needsAction = snapshot.entities.find((entityArg) => entityArg.id === 'needs_action');
  const completed = snapshot.entities.find((entityArg) => entityArg.id === 'completed');

  expect(snapshot.online).toBeTrue();
  expect(snapshot.device.name).toEqual('House Tasks');
  expect(items?.state).toEqual(2);
  expect(needsAction?.state).toEqual(1);
  expect(completed?.state).toEqual(1);
  expect(JSON.stringify(items?.attributes?.items)).toContain('"due":"2026-05-12"');
  expect(JSON.stringify(localTodoProfile.metadata.localApi)).toContain('local ICS file');

  const runtime = await new LocalTodoIntegration().setup({ name: 'House Tasks', filePath: 'test/local_todo/sample.ics' }, {});
  const status = await runtime.callService!({ domain: 'local_todo', service: 'status', target: {} });
  const runtimeSnapshot = status.data as ILocalTodoSnapshot;
  expect(status.success).toBeTrue();
  expect(runtimeSnapshot.entities.find((entityArg) => entityArg.id === 'todo_items')?.state).toEqual(2);
  await runtime.destroy();
});

tap.test('exposes Local To-do runtime, HA alias, and unsupported control without executor', async () => {
  const integration = new LocalTodoIntegration();
  const alias = new HomeAssistantLocalTodoIntegration();
  expect(alias instanceof LocalTodoIntegration).toBeTrue();
  expect(alias.domain).toEqual("local_todo");
  expect(integration.status).toEqual("read-only-runtime");
  expect(localTodoProfile.metadata.configFlow).toEqual(true);
  expect(localTodoProfile.metadata.requirements).toEqual([
    "ical==13.2.2",
  ]);

  const runtime = await integration.setup({ name: "Local To-do Runtime", rawData }, {});
  const statusResult = await runtime.callService!({ domain: "local_todo", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "local_todo", service: 'refresh', target: {} });
  const snapshot = statusResult.data as ILocalTodoSnapshot;

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

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