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 { ZhaClient } from './zha.classes.client.js';
import { ZhaConfigFlow } from './zha.classes.configflow.js';
import { createZhaDiscoveryDescriptor } from './zha.discovery.js';
import { ZhaMapper } from './zha.mapper.js';
import type { IZhaClientCommand, IZhaConfig } from './zha.types.js';

export class ZhaIntegration extends BaseIntegration<IZhaConfig> {
  public readonly domain = 'zha';
  public readonly displayName = 'Zigbee Home Automation';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createZhaDiscoveryDescriptor();
  public readonly configFlow = new ZhaConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/zha',
    upstreamDomain: 'zha',
    integrationType: 'hub',
    iotClass: 'local_polling',
    qualityScale: 'unknown',
  };

  public async setup(configArg: IZhaConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new ZhaRuntime(new ZhaClient(configArg));
  }

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

export class HomeAssistantZhaIntegration extends ZhaIntegration {}

class ZhaRuntime implements IIntegrationRuntime {
  public domain = 'zha';

  constructor(private readonly client: ZhaClient) {}

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

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

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

  private commandFromService(requestArg: IServiceCallRequest): IZhaClientCommand | undefined {
    if (requestArg.service === 'issue_zigbee_cluster_command') {
      return {
        type: 'cluster.command',
        service: requestArg.service,
        ieee: this.stringValue(requestArg.data?.ieee),
        endpointId: this.numberValue(requestArg.data?.endpoint_id ?? requestArg.data?.endpointId),
        clusterId: this.numberValue(requestArg.data?.cluster_id ?? requestArg.data?.clusterId),
        clusterType: this.stringValue(requestArg.data?.cluster_type ?? requestArg.data?.clusterType),
        command: requestArg.data?.command as string | number | undefined,
        args: Array.isArray(requestArg.data?.args) ? requestArg.data.args : undefined,
        params: this.isRecord(requestArg.data?.params) ? requestArg.data.params : undefined,
        payload: { ...requestArg.data },
        target: requestArg.target,
      };
    }
    if (requestArg.service === 'set_zigbee_cluster_attribute') {
      return {
        type: 'cluster.write_attribute',
        service: requestArg.service,
        ieee: this.stringValue(requestArg.data?.ieee),
        endpointId: this.numberValue(requestArg.data?.endpoint_id ?? requestArg.data?.endpointId),
        clusterId: this.numberValue(requestArg.data?.cluster_id ?? requestArg.data?.clusterId),
        clusterType: this.stringValue(requestArg.data?.cluster_type ?? requestArg.data?.clusterType),
        attribute: requestArg.data?.attribute as string | number | undefined,
        value: requestArg.data?.value,
        payload: { ...requestArg.data },
        target: requestArg.target,
      };
    }
    if (requestArg.service === 'permit') {
      return {
        type: 'network.permit',
        service: requestArg.service,
        payload: { duration: requestArg.data?.duration ?? 60 },
        target: requestArg.target,
      };
    }
    return undefined;
  }

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' ? valueArg : undefined;
  }

  private numberValue(valueArg: unknown): number | undefined {
    return typeof valueArg === 'number' && Number.isFinite(valueArg) ? valueArg : undefined;
  }

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