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 { HomekitControllerClient } from './homekit_controller.classes.client.js';
import { HomekitControllerConfigFlow } from './homekit_controller.classes.configflow.js';
import { createHomekitControllerDiscoveryDescriptor } from './homekit_controller.discovery.js';
import { HomekitControllerMapper } from './homekit_controller.mapper.js';
import type { IHomekitControllerConfig } from './homekit_controller.types.js';

export class HomekitControllerIntegration extends BaseIntegration<IHomekitControllerConfig> {
  public readonly domain = 'homekit_controller';
  public readonly displayName = 'HomeKit Device';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createHomekitControllerDiscoveryDescriptor();
  public readonly configFlow = new HomekitControllerConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/homekit_controller',
    upstreamDomain: 'homekit_controller',
    integrationType: 'device',
    iotClass: 'local_push',
    requirements: ['aiohomekit==3.2.20'],
    dependencies: ['bluetooth_adapters', 'zeroconf'],
    afterDependencies: ['thread'],
    codeowners: ['@Jc2k', '@bdraco'],
    zeroconf: ['_hap._tcp.local.', '_hap._udp.local.'],
    documentation: 'https://www.home-assistant.io/integrations/homekit_controller',
  };

  public async setup(configArg: IHomekitControllerConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new HomekitControllerRuntime(new HomekitControllerClient(configArg));
  }

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

export class HomeAssistantHomekitControllerIntegration extends HomekitControllerIntegration {}

class HomekitControllerRuntime implements IIntegrationRuntime {
  public domain = 'homekit_controller';

  constructor(private readonly client: HomekitControllerClient) {}

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

  public async entities(): Promise<IIntegrationEntity[]> {
    return HomekitControllerMapper.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 === 'error' ? 'error' : 'state_changed',
        integrationDomain: 'homekit_controller',
        deviceId: typeof eventArg.aid === 'number' ? `homekit_controller.accessory.${eventArg.aid}` : undefined,
        data: eventArg,
        timestamp: eventArg.timestamp,
      });
    });
    await this.client.getSnapshot();
    return async () => unsubscribe();
  }

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const snapshot = await this.client.getSnapshot();
    const command = HomekitControllerMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `HomeKit Controller service ${requestArg.domain}.${requestArg.service} has no characteristic mapping.` };
    }
    try {
      const data = await this.client.execute(command);
      return { success: true, data };
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : String(error) };
    }
  }

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