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 { EsphomeClient } from './esphome.classes.client.js';
import { EsphomeConfigFlow } from './esphome.classes.configflow.js';
import { createEsphomeDiscoveryDescriptor } from './esphome.discovery.js';
import { EsphomeMapper } from './esphome.mapper.js';
import type { IEsphomeClientCommand, IEsphomeConfig } from './esphome.types.js';

export class EsphomeIntegration extends BaseIntegration<IEsphomeConfig> {
  public readonly domain = 'esphome';
  public readonly displayName = 'ESPHome';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createEsphomeDiscoveryDescriptor();
  public readonly configFlow = new EsphomeConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/esphome',
    upstreamDomain: 'esphome',
    integrationType: 'device',
    iotClass: 'local_push',
    qualityScale: 'platinum',
    requirements: [
      'aioesphomeapi==44.21.0',
      'esphome-dashboard-api==1.3.0',
      'bleak-esphome==3.7.3',
    ],
    dependencies: ['assist_pipeline', 'bluetooth', 'intent', 'ffmpeg', 'http'],
    afterDependencies: ['hassio', 'tag', 'usb', 'zeroconf'],
    codeowners: ['@jesserockz', '@kbx81', '@bdraco'],
    documentation: 'https://www.home-assistant.io/integrations/esphome',
    zeroconf: ['_esphomelib._tcp.local.'],
    mqtt: ['esphome/discover/#'],
  };

  public async setup(configArg: IEsphomeConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new EsphomeRuntime(new EsphomeClient(configArg));
  }

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

export class HomeAssistantEsphomeIntegration extends EsphomeIntegration {}

class EsphomeRuntime implements IIntegrationRuntime {
  public domain = 'esphome';

  constructor(private readonly client: EsphomeClient) {}

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

  public async entities(): Promise<IIntegrationEntity[]> {
    return EsphomeMapper.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_mapped' ? 'state_changed' : 'error',
        integrationDomain: 'esphome',
        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 = requestArg.domain === 'esphome'
      ? this.esphomeCommandFromService(requestArg)
      : EsphomeMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `ESPHome 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();
  }

  private esphomeCommandFromService(requestArg: IServiceCallRequest): IEsphomeClientCommand | undefined {
    if (requestArg.service === 'send_command' && this.isRecord(requestArg.data?.command)) {
      return requestArg.data.command as unknown as IEsphomeClientCommand;
    }
    if (requestArg.service === 'execute_service' || requestArg.service === 'execute_action') {
      const name = requestArg.data?.name;
      if (typeof name !== 'string' || !name) {
        return undefined;
      }
      return {
        type: 'execute_service',
        service: name,
        payload: this.isRecord(requestArg.data?.data) ? requestArg.data.data : {},
        target: requestArg.target,
      };
    }
    return {
      type: 'execute_service',
      service: requestArg.service,
      payload: requestArg.data || {},
      target: requestArg.target,
    };
  }

  private isRecord(valueArg: unknown): valueArg is Record<string, unknown> {
    return typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg);
  }
}
