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 { XiaomiMiioClient } from './xiaomi_miio.classes.client.js';
import { XiaomiMiioConfigFlow } from './xiaomi_miio.classes.configflow.js';
import { createXiaomiMiioDiscoveryDescriptor } from './xiaomi_miio.discovery.js';
import { XiaomiMiioMapper } from './xiaomi_miio.mapper.js';
import type { IXiaomiMiioConfig } from './xiaomi_miio.types.js';

export class XiaomiMiioIntegration extends BaseIntegration<IXiaomiMiioConfig> {
  public readonly domain = 'xiaomi_miio';
  public readonly displayName = 'Xiaomi Home';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createXiaomiMiioDiscoveryDescriptor();
  public readonly configFlow = new XiaomiMiioConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/xiaomi_miio',
    upstreamDomain: 'xiaomi_miio',
    documentation: 'https://www.home-assistant.io/integrations/xiaomi_miio',
    integrationType: 'hub',
    iotClass: 'local_polling',
    requirements: ['construct==2.10.68', 'micloud==0.5', 'python-miio==0.5.12'],
    zeroconf: ['_miio._udp.local.'],
    codeowners: ['@rytilahti', '@syssi', '@starkillerOG'],
  };

  public async setup(configArg: IXiaomiMiioConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new XiaomiMiioRuntime(new XiaomiMiioClient(configArg));
  }

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

export class HomeAssistantXiaomiMiioIntegration extends XiaomiMiioIntegration {}

class XiaomiMiioRuntime implements IIntegrationRuntime {
  public domain = 'xiaomi_miio';

  constructor(private readonly client: XiaomiMiioClient) {}

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

  public async entities(): Promise<IIntegrationEntity[]> {
    return XiaomiMiioMapper.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 === 'availability_changed' ? 'availability_changed' : eventArg.type === 'device_removed' ? 'device_removed' : 'state_changed',
        integrationDomain: 'xiaomi_miio',
        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 command = XiaomiMiioMapper.commandForService(await this.client.getSnapshot(), requestArg);
    if (!command) {
      return { success: false, error: `Unsupported Xiaomi Miio service: ${requestArg.domain}.${requestArg.service}` };
    }
    return this.client.sendCommand(command);
  }

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