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 { RainbirdClient } from './rainbird.classes.client.js';
import { RainbirdConfigFlow } from './rainbird.classes.configflow.js';
import { createRainbirdDiscoveryDescriptor } from './rainbird.discovery.js';
import { RainbirdMapper } from './rainbird.mapper.js';
import type { IRainbirdConfig } from './rainbird.types.js';

export class RainbirdIntegration extends BaseIntegration<IRainbirdConfig> {
  public readonly domain = 'rainbird';
  public readonly displayName = 'Rain Bird';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createRainbirdDiscoveryDescriptor();
  public readonly configFlow = new RainbirdConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/rainbird',
    upstreamDomain: 'rainbird',
    integrationType: 'hub',
    iotClass: 'local_polling',
    requirements: ['pyrainbird==6.3.0'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@konikvranik', '@allenporter'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/rainbird',
    discovery: {
      manual: true,
      dhcp: false,
      mdns: false,
      note: 'Home Assistant Rain Bird manifest has no dhcp or zeroconf discovery entries; manual local host/password setup is implemented.',
    },
    runtime: {
      type: 'control-runtime',
      polling: 'local snapshot',
      services: ['start_zone', 'stop_zone', 'set_rain_delay', 'refresh', 'start_irrigation'],
    },
    localApi: {
      implemented: [
        'AES-256-CBC encrypted JSON-RPC POST /stick payloads from pyrainbird PayloadCoder',
        'tunnelSip ModelAndVersionRequest',
        'tunnelSip SerialNumberRequest',
        'getWifiParams JSON-RPC',
        'tunnelSip AvailableStationsRequest',
        'tunnelSip CurrentStationsActiveRequest',
        'tunnelSip CurrentRainSensorStateRequest',
        'tunnelSip RainDelayGetRequest/RainDelaySetRequest',
        'tunnelSip ManuallyRunStationRequest/StopIrrigationRequest/ManuallyRunProgramRequest',
      ],
      explicitUnsupported: [
        'cloud relay API',
        'full schedule timeline decoding in the live client',
        'HTTPS controllers with self-signed certificates when runtime fetch rejects the certificate',
      ],
    },
  };

  public async setup(configArg: IRainbirdConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new RainbirdRuntime(new RainbirdClient(configArg));
  }

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

export class HomeAssistantRainbirdIntegration extends RainbirdIntegration {}

class RainbirdRuntime implements IIntegrationRuntime {
  public domain = 'rainbird';

  constructor(private readonly client: RainbirdClient) {}

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

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

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

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