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 { OpnsenseClient } from './opnsense.classes.client.js';
import { OpnsenseConfigFlow } from './opnsense.classes.configflow.js';
import { createOpnsenseDiscoveryDescriptor } from './opnsense.discovery.js';
import { OpnsenseMapper } from './opnsense.mapper.js';
import type { IOpnsenseConfig } from './opnsense.types.js';
import { opnsenseDomain } from './opnsense.types.js';

export class OpnsenseIntegration extends BaseIntegration<IOpnsenseConfig> {
  public readonly domain = opnsenseDomain;
  public readonly displayName = 'OPNsense';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createOpnsenseDiscoveryDescriptor();
  public readonly configFlow = new OpnsenseConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/opnsense',
    upstreamDomain: opnsenseDomain,
    integrationType: 'hub',
    iotClass: 'local_polling',
    qualityScale: 'legacy',
    requirements: ['aiopnsense==1.0.8'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@HarlemSquirrel', '@Snuffy2'],
    documentation: 'https://www.home-assistant.io/integrations/opnsense',
    runtime: {
      mode: 'native TypeScript snapshot/manual OPNsense mapping',
      platforms: ['binary_sensor', 'button', 'device_tracker', 'sensor', 'switch', 'update'],
      services: ['refresh', 'snapshot', 'status', 'reboot', 'halt', 'start_service', 'stop_service', 'restart_service', 'reload_interface', 'firmware_update', 'upgrade_firmware', 'close_notice', 'send_wol', 'run_speedtest'],
    },
    localApi: {
      implemented: [
        'manual and local HTTPS OPNsense setup candidates plus config flow matching Home Assistant api_key/api_secret/verify_ssl/tracker_interfaces inputs',
        'Home Assistant legacy device_tracker-style ARP table mapping filtered by interface description',
        'snapshot mapping for system, firewall/NAT/aliases, interfaces, gateways, VPN, services, telemetry sensors, generic sensors, and switches where represented',
        'safe command modeling for represented router, service, firewall, NAT, alias, VPN, interface, firmware, notice, Wake-on-LAN, speedtest, and switch actions',
      ],
      explicitUnsupported: [
        'Home Assistant compatibility shims',
        'fake OPNsense HTTPS API connection, validation, or command success without commandExecutor/nativeClient injection',
        'full aiopnsense live HTTP implementation in dependency-free TypeScript',
      ],
    },
  };

  public async setup(configArg: IOpnsenseConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new OpnsenseRuntime(new OpnsenseClient(configArg));
  }

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

export class HomeAssistantOpnsenseIntegration extends OpnsenseIntegration {}

class OpnsenseRuntime implements IIntegrationRuntime {
  public domain = opnsenseDomain;

  constructor(private readonly client: OpnsenseClient) {}

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

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

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

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

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