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 { AirosClient } from './airos.classes.client.js';
import { AirosConfigFlow } from './airos.classes.configflow.js';
import { airosDefaultName, airosDisplayName, airosDomain } from './airos.constants.js';
import { createAirosDiscoveryDescriptor } from './airos.discovery.js';
import { AirosMapper } from './airos.mapper.js';
import type { IAirosConfig } from './airos.types.js';

export class AirosIntegration extends BaseIntegration<IAirosConfig> {
  public readonly domain = airosDomain;
  public readonly displayName = airosDisplayName;
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createAirosDiscoveryDescriptor();
  public readonly configFlow = new AirosConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/airos',
    upstreamDomain: airosDomain,
    integrationType: 'device',
    iotClass: 'local_polling',
    qualityScale: 'platinum',
    requirements: ['airos==0.6.5'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@CoMPaTech'],
    documentation: 'https://www.home-assistant.io/integrations/airos',
    configFlow: true,
    discovery: {
      dhcp: ['registered_devices:true'],
      custom: ['UDP broadcast listener on port 10002 using python-airos packet format'],
      manual: true,
      note: 'Home Assistant declares DHCP registered-device discovery. This native port supports that signal, native UDP airOS broadcasts, and manual host/snapshot/raw-status candidates.',
    },
    runtime: {
      type: 'control-runtime',
      polling: 'local airOS web API status.cgi/update-check or supplied snapshot/nativeClient',
      platforms: ['binary_sensor', 'button', 'sensor', 'update'],
      services: ['airos.snapshot', 'airos.refresh', 'airos.reboot', 'airos.firmware_update_check', 'airos.download_update', 'airos.install_update', 'button.press', 'update.install'],
    },
    localApi: {
      implemented: [
        'DHCP registered-device/manual matching and native UDP broadcast packet parsing/listening on port 10002',
        'Config flow shape for host, username, password, HTTPS, verify SSL, native HTTP, port, timeout, snapshot JSON, raw status JSON, and firmware JSON',
        'Native airOS 8 /api/auth login, status.cgi snapshots, update-check, firmware download/install, and reboot.cgi where host/password are configured',
        'Fallback airOS 6 login.cgi session login for status.cgi snapshots and reboot.cgi; firmware update actions remain airOS 8 only by endpoint availability',
        'Snapshot-to-device/entity mapper for Home Assistant sensors, binary sensors, reboot button, and firmware update entity',
      ],
      explicitUnsupported: [
        'UISP cloud APIs',
        'Station kick/provisioning-mode commands as runtime services because Home Assistant airos does not expose them as entities/services',
        'Claiming command success without host/password native HTTP, nativeClient command method, commandExecutor, or transport.execute',
      ],
    },
  };

  public async setup(configArg: IAirosConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new AirosRuntime(new AirosClient(configArg));
  }

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

export class HomeAssistantAirosIntegration extends AirosIntegration {}

class AirosRuntime implements IIntegrationRuntime {
  public domain = airosDomain;

  constructor(private readonly client: AirosClient) {}

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

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    if (requestArg.domain === airosDomain && (requestArg.service === 'snapshot' || requestArg.service === 'status')) {
      return { success: true, data: await this.client.getSnapshot() };
    }
    if (requestArg.domain === airosDomain && requestArg.service === 'refresh') {
      return this.client.refresh();
    }
    const snapshot = await this.client.getSnapshot();
    const command = AirosMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `Unsupported airOS service or target: ${requestArg.domain}.${requestArg.service}` };
    }
    return this.client.sendCommand(command);
  }

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