import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { BaseIntegration } from '../../core/classes.baseintegration.js';
import type { IIntegrationEntity, IIntegrationEvent, IIntegrationRuntime, IIntegrationSetupContext, IServiceCallRequest, IServiceCallResult } from '../../core/types.js';
import { TradfriClient } from './tradfri.classes.client.js';
import { TradfriConfigFlow } from './tradfri.classes.configflow.js';
import { createTradfriDiscoveryDescriptor } from './tradfri.discovery.js';
import { TradfriMapper } from './tradfri.mapper.js';
import type { ITradfriConfig } from './tradfri.types.js';

export class TradfriIntegration extends BaseIntegration<ITradfriConfig> {
  public readonly domain = 'tradfri';
  public readonly displayName = 'IKEA TR\u00c5DFRI';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createTradfriDiscoveryDescriptor();
  public readonly configFlow = new TradfriConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/tradfri',
    upstreamDomain: 'tradfri',
    integrationType: 'hub',
    iotClass: 'local_polling',
    requirements: ['pytradfri[async]==9.0.1'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: [] as string[],
    documentation: 'https://www.home-assistant.io/integrations/tradfri',
    homekit: { models: ['TRADFRI'] },
    configFlow: true,
  };

  public async setup(configArg: ITradfriConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new TradfriRuntime(new TradfriClient(configArg));
  }

  public async destroy(): Promise<void> {}
}

export class HomeAssistantTradfriIntegration extends TradfriIntegration {}

class TradfriRuntime implements IIntegrationRuntime {
  public domain = 'tradfri';

  constructor(private readonly client: TradfriClient) {}

  public async devices(): Promise<shxInterfaces.data.IDeviceDefinition[]> {
    return TradfriMapper.toDevices(await this.client.getSnapshot());
  }

  public async entities(): Promise<IIntegrationEntity[]> {
    return TradfriMapper.toEntities(await this.client.getSnapshot());
  }

  public async subscribe(handlerArg: (eventArg: IIntegrationEvent) => void): Promise<() => Promise<void>> {
    const unsubscribe = this.client.onEvent((eventArg) => {
      handlerArg({
        type: eventArg.type === 'command_failed' ? 'error' : 'state_changed',
        integrationDomain: 'tradfri',
        deviceId: eventArg.deviceId,
        entityId: eventArg.entityId,
        data: eventArg,
        timestamp: eventArg.timestamp || Date.now(),
      });
    });
    await this.client.getSnapshot();
    return async () => unsubscribe();
  }

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const snapshot = await this.client.getSnapshot();
    const command = TradfriMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `IKEA Tradfri service ${requestArg.domain}.${requestArg.service} has no safe native command mapping.` };
    }
    const result = await this.client.sendCommand(command);
    return { success: result.success, error: result.error, data: result.data };
  }

  public async destroy(): Promise<void> {
    await this.client.destroy();
  }
}
