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 { WizClient } from './wiz.classes.client.js';
import { WizConfigFlow } from './wiz.classes.configflow.js';
import { createWizDiscoveryDescriptor } from './wiz.discovery.js';
import { WizMapper } from './wiz.mapper.js';
import type { IWizConfig } from './wiz.types.js';

export class WizIntegration extends BaseIntegration<IWizConfig> {
  public readonly domain = 'wiz';
  public readonly displayName = 'WiZ';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createWizDiscoveryDescriptor();
  public readonly configFlow = new WizConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/wiz',
    upstreamDomain: 'wiz',
    integrationType: 'device',
    iotClass: 'local_push',
    requirements: ['pywizlight==0.6.3'],
    dependencies: ['network'],
    afterDependencies: [] as string[],
    codeowners: ['@sbidy', '@arturpragacz'],
    documentation: 'https://www.home-assistant.io/integrations/wiz',
    protocolDocumentation: 'https://docs.pro.wizconnected.com/#introduction',
    dhcp: [
      { registeredDevices: true },
      { macaddress: 'A8BB50*' },
      { macaddress: 'D8A011*' },
      { macaddress: '444F8E*' },
      { macaddress: '6C2990*' },
      { hostname: 'wiz_*' },
    ],
  };

  public async setup(configArg: IWizConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new WizRuntime(new WizClient(configArg));
  }

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

export class HomeAssistantWizIntegration extends WizIntegration {}

class WizRuntime implements IIntegrationRuntime {
  public domain = 'wiz';

  constructor(private readonly client: WizClient) {}

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

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

  public async subscribe(handlerArg: (eventArg: IIntegrationEvent) => void): Promise<() => Promise<void>> {
    const unsubscribe = this.client.onEvent((eventArg) => handlerArg(WizMapper.toIntegrationEvent(eventArg)));
    await this.client.getSnapshot();
    return async () => unsubscribe();
  }

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const snapshot = await this.client.getSnapshot();
    const command = WizMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `WiZ service ${requestArg.domain}.${requestArg.service} has no native setPilot mapping for the target.` };
    }
    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();
  }
}
