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 { BroadlinkClient } from './broadlink.classes.client.js';
import { BroadlinkConfigFlow } from './broadlink.classes.configflow.js';
import { createBroadlinkDiscoveryDescriptor } from './broadlink.discovery.js';
import { BroadlinkMapper } from './broadlink.mapper.js';
import type { IBroadlinkConfig } from './broadlink.types.js';

export class BroadlinkIntegration extends BaseIntegration<IBroadlinkConfig> {
  public readonly domain = 'broadlink';
  public readonly displayName = 'Broadlink';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createBroadlinkDiscoveryDescriptor();
  public readonly configFlow = new BroadlinkConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/broadlink',
    upstreamDomain: 'broadlink',
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['broadlink==0.19.0'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@danielhiversen', '@felipediel', '@L-I-Am', '@eifinger'],
    documentation: 'https://www.home-assistant.io/integrations/broadlink',
    configFlow: true,
    discovery: {
      dhcp: true,
      manual: true,
      localHelloRecords: true,
      note: 'Home Assistant uses python-broadlink UDP hello/auth. This native port recognizes DHCP/manual/local hello candidates; live UDP is an injected executor boundary.',
    },
    runtime: {
      type: 'control-runtime',
      polling: 'snapshot/manual',
      services: ['remote.send_command', 'remote.learn_command', 'remote.delete_command', 'switch.turn_on', 'switch.turn_off', 'infrared.send_command', 'radio_frequency.send_command', 'broadlink.send_packet'],
      liveUdpAuthImplemented: false,
    },
    localApi: {
      implemented: [
        'Broadlink DHCP/manual/local hello discovery candidate mapping',
        'Config flow shape for host, MAC, device type, timeout, and optional snapshot JSON',
        'Snapshot mapping for RM remote entities, Broadlink switch/outlet slots, custom IR/RF switches, and safe sensor keys',
        'Packet encoding for Broadlink IR timings and 315/433 MHz RF timings',
        'Explicit service command shapes for learned-code send/delete, learn IR/RF, send packet, switch power, IR, and RF commands',
      ],
      explicitUnsupported: [
        'Native Broadlink UDP discovery broadcast from this package',
        'Native Broadlink encrypted UDP auth/session transport',
        'Claiming live packets were sent without an injected commandExecutor or transport.execute',
      ],
    },
  };

  public async setup(configArg: IBroadlinkConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new BroadlinkRuntime(new BroadlinkClient(configArg));
  }

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

export class HomeAssistantBroadlinkIntegration extends BroadlinkIntegration {}

class BroadlinkRuntime implements IIntegrationRuntime {
  public domain = 'broadlink';

  constructor(private readonly client: BroadlinkClient) {}

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

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

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

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