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 { WakeOnLanClient } from './wake_on_lan.classes.client.js';
import { WakeOnLanConfigFlow } from './wake_on_lan.classes.configflow.js';
import { createWakeOnLanDiscoveryDescriptor } from './wake_on_lan.discovery.js';
import { WakeOnLanMapper } from './wake_on_lan.mapper.js';
import type { IWakeOnLanConfig } from './wake_on_lan.types.js';
import { wakeOnLanDomain } from './wake_on_lan.constants.js';

export class WakeOnLanIntegration extends BaseIntegration<IWakeOnLanConfig> {
  public readonly domain = wakeOnLanDomain;
  public readonly displayName = 'Wake on LAN';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createWakeOnLanDiscoveryDescriptor();
  public readonly configFlow = new WakeOnLanConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/wake_on_lan',
    upstreamDomain: wakeOnLanDomain,
    integrationType: 'service',
    iotClass: 'local_push',
    requirements: ['wakeonlan==3.1.0'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@ntilley905'],
    documentation: 'https://www.home-assistant.io/integrations/wake_on_lan',
    configFlow: true,
    runtime: {
      type: 'control-runtime',
      polling: 'snapshot/manual with optional pingExecutor',
      platforms: ['button', 'switch'],
      services: ['wake_on_lan.send_magic_packet', 'button.press', 'switch.turn_on', 'switch.turn_off'],
    },
    localApi: {
      implemented: [
        'Manual/static host and MAC discovery candidates',
        'Config flow shape for MAC, host, broadcast address, broadcast port, and button/switch entity mode',
        'Home Assistant-compatible Wake-on-LAN magic packet construction',
        'Native UDP magic packet send with explicit success/failure from the socket callback',
        'Runtime service mapping for wake_on_lan.send_magic_packet, button.press, and switch turn_on/turn_off entities',
      ],
      explicitUnsupported: [
        'homeassistant_compat shims',
        'Claiming send success when native UDP is disabled and no commandExecutor/transport.execute is provided',
        'Executing Home Assistant turn_off scripts without an injected executor',
      ],
    },
  };

  public async setup(configArg: IWakeOnLanConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new WakeOnLanRuntime(new WakeOnLanClient(configArg));
  }

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

export class HomeAssistantWakeOnLanIntegration extends WakeOnLanIntegration {}

class WakeOnLanRuntime implements IIntegrationRuntime {
  public domain = wakeOnLanDomain;

  constructor(private readonly client: WakeOnLanClient) {}

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

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.domain === wakeOnLanDomain && (requestArg.service === 'snapshot' || requestArg.service === 'status')) {
      return { success: true, data: await this.client.getSnapshot() };
    }
    if (requestArg.domain === wakeOnLanDomain && requestArg.service === 'refresh') {
      return this.client.refresh();
    }
    const snapshot = await this.client.getSnapshot();
    const command = WakeOnLanMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: this.unsupportedServiceMessage(requestArg) };
    }
    return this.client.sendCommand(command);
  }

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

  private unsupportedServiceMessage(requestArg: IServiceCallRequest): string {
    if (requestArg.domain === wakeOnLanDomain && requestArg.service === 'send_magic_packet') {
      return 'Wake on LAN send_magic_packet requires a valid MAC address from service data or a configured target.';
    }
    return `Unsupported Wake on LAN service or target: ${requestArg.domain}.${requestArg.service}`;
  }
}
