import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LocalCalendarClient, LocalCalendarConfigFlow, LocalCalendarIntegration, LocalCalendarMapper, createLocalCalendarDiscoveryDescriptor, localCalendarProfile, type ILocalCalendarSnapshot, type TLocalCalendarRawData } from '../../ts/integrations/local_calendar/index.js';

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

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

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

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

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

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

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

tap.test('reads Local Calendar events from a local ICS file', async () => {
  const client = new LocalCalendarClient({ name: 'Maintenance Calendar', filePath: 'test/local_calendar/sample.ics' });
  const snapshot = await client.getSnapshot(true);
  const entities = LocalCalendarMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.device.model).toEqual('Local iCalendar file');
  expect(snapshot.entities.find((entityArg) => entityArg.id === 'event_count')?.state).toEqual(2);
  expect(snapshot.entities.find((entityArg) => entityArg.id === 'next_event')?.state).toEqual('Future Maintenance');
  expect(snapshot.entities.find((entityArg) => entityArg.id === 'next_event')?.attributes?.location).toEqual('Utility Room');
  expect(entities.find((entityArg) => entityArg.id === 'sensor.maintenance_calendar_next_event')?.state).toEqual('Future Maintenance');

  const runtime = await new LocalCalendarIntegration().setup({ name: 'Maintenance Calendar', icsFile: 'test/local_calendar/sample.ics' }, {});
  const status = await runtime.callService!({ domain: 'local_calendar', service: 'status', target: {} });
  const runtimeSnapshot = status.data as ILocalCalendarSnapshot;

  expect(status.success).toBeTrue();
  expect(runtimeSnapshot.entities.find((entityArg) => entityArg.id === 'event_count')?.state).toEqual(2);
  await runtime.destroy();
});

tap.test('exposes Local Calendar runtime and unsupported control without executor', async () => {
  const integration = new LocalCalendarIntegration();
  expect(integration.status).toEqual("read-only-runtime");
  expect(localCalendarProfile.metadata.configFlow).toEqual(true);
  expect(localCalendarProfile.metadata.requirements).toEqual([
    "ical==13.2.2",
  ]);

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

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

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