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 { AirgradientClient } from './airgradient.classes.client.js';
import { AirgradientConfigFlow } from './airgradient.classes.configflow.js';
import { createAirgradientDiscoveryDescriptor } from './airgradient.discovery.js';
import { AirgradientMapper } from './airgradient.mapper.js';
import type { IAirgradientConfig } from './airgradient.types.js';

export class AirgradientIntegration extends BaseIntegration<IAirgradientConfig> {
  public readonly domain = 'airgradient';
  public readonly displayName = 'AirGradient';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createAirgradientDiscoveryDescriptor();
  public readonly configFlow = new AirgradientConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/airgradient',
    upstreamDomain: 'airgradient',
    integrationType: 'device',
    iotClass: 'local_polling',
    qualityScale: 'platinum',
    requirements: ['airgradient==0.9.2'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@airgradienthq', '@joostlek'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/airgradient',
    zeroconf: ['_airgradient._tcp.local.'],
    runtime: {
      type: 'control-runtime',
      polling: 'local HTTP snapshot',
      endpoints: ['GET /measures/current', 'GET /config', 'PUT /config'],
      services: ['set_config', 'request_co2_calibration', 'request_led_bar_test', 'refresh'],
    },
  };

  public async setup(configArg: IAirgradientConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new AirgradientRuntime(new AirgradientClient(configArg));
  }

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

export class HomeAssistantAirgradientIntegration extends AirgradientIntegration {}

class AirgradientRuntime implements IIntegrationRuntime {
  public domain = 'airgradient';

  constructor(private readonly client: AirgradientClient) {}

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

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const snapshot = await this.client.getSnapshot();
    const command = AirgradientMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `Unsupported AirGradient service: ${requestArg.domain}.${requestArg.service}` };
    }
    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();
  }
}
