import { expect, tap } from '@git.zone/tstest/tapbundle';
import { LocalFileClient, LocalFileConfigFlow, LocalFileIntegration, LocalFileMapper, createLocalFileDiscoveryDescriptor, localFileProfile, type ILocalFileSnapshot, type TLocalFileRawData } from '../../ts/integrations/local_file/index.js';

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

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

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

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

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

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

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

tap.test('reads Local File image bytes from a local path and updates the path natively', async () => {
  const client = new LocalFileClient({ name: 'Door Camera', filePath: 'test/local_file/sample-one.png' });
  const snapshot = await client.getSnapshot(true);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.device.model).toEqual('Local File Camera');
  expect(snapshot.entities[0].state).toEqual(17);
  expect(snapshot.entities[0].attributes?.contentType).toEqual('image/png');

  const update = await client.execute({ domain: 'local_file', service: 'update_file_path', target: {}, data: { file_path: 'test/local_file/sample-two.jpg' } });
  const updatedSnapshot = update.data as ILocalFileSnapshot;

  expect(update.success).toBeTrue();
  expect(updatedSnapshot.entities[0].state).toEqual(17);
  expect(updatedSnapshot.entities[0].attributes?.contentType).toEqual('image/jpeg');
  expect(updatedSnapshot.entities[0].attributes?.file_path).toEqual('test/local_file/sample-two.jpg');
});

tap.test('exposes Local File runtime, native path update, and unsupported non-native control without executor', async () => {
  const integration = new LocalFileIntegration();
  expect(integration.status).toEqual("control-runtime");
  expect(localFileProfile.metadata.configFlow).toEqual(true);

  const runtime = await integration.setup({ name: "Local File Runtime", filePath: 'test/local_file/sample-one.png' }, {});
  const statusResult = await runtime.callService!({ domain: "local_file", service: 'status', target: {} });
  const refresh = await runtime.callService!({ domain: "local_file", service: 'refresh', target: {} });
  const snapshot = statusResult.data as ILocalFileSnapshot;

  expect(statusResult.success).toBeTrue();
  expect(refresh.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect(snapshot.entities[0].attributes?.contentType).toEqual('image/png');
  expect((await runtime.devices())[0].name).toEqual("Local File Runtime");

  const update = await runtime.callService!({ domain: "local_file", service: 'update_file_path', target: {}, data: { file_path: 'test/local_file/sample-two.jpg' } });
  expect(update.success).toBeTrue();
  expect(((update.data as ILocalFileSnapshot).entities[0].attributes?.contentType)).toEqual('image/jpeg');

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