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 { FritzClient } from './fritz.classes.client.js';
import { FritzConfigFlow } from './fritz.classes.configflow.js';
import { createFritzDiscoveryDescriptor } from './fritz.discovery.js';
import { FritzMapper } from './fritz.mapper.js';
import type { IFritzConfig } from './fritz.types.js';
import { fritzDomain } from './fritz.types.js';

export class FritzIntegration extends BaseIntegration<IFritzConfig> {
  public readonly domain = fritzDomain;
  public readonly displayName = 'FRITZ!Box Tools';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createFritzDiscoveryDescriptor();
  public readonly configFlow = new FritzConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/fritz',
    upstreamDomain: fritzDomain,
    integrationType: 'hub',
    iotClass: 'local_polling',
    qualityScale: 'gold',
    requirements: ['fritzconnection[qr]==1.15.1', 'xmltodict==1.0.4'],
    dependencies: ['network'],
    afterDependencies: [] as string[],
    codeowners: ['@AaronDavidSchneider', '@chemelli74', '@mib1185'],
    documentation: 'https://www.home-assistant.io/integrations/fritz',
    configFlow: true,
    runtime: {
      mode: 'native TypeScript snapshot/manual FRITZ!Box mapping',
      platforms: ['binary_sensor', 'button', 'device_tracker', 'sensor', 'switch', 'update'],
      services: ['refresh', 'snapshot', 'reboot', 'reconnect', 'firmware_update', 'cleanup', 'set_guest_wifi_password', 'dial', 'wake_on_lan'],
    },
    localApi: {
      implemented: [
        'manual FRITZ!Box setup candidates and config flow',
        'SSDP FRITZ!Box device-type candidates matching Home Assistant manifest support',
        'snapshot mapping for router connection sensors, traffic counters/rates, interfaces, client presence/device-tracker equivalents, Wi-Fi, port forwarding, call deflection, internet-access, WOL, and FRITZ!OS update controls',
        'safe command modeling for explicitly represented router, client, switch, update, and service actions',
      ],
      explicitUnsupported: [
        'homeassistant_compat shims',
        'fake FRITZ!Box TR-064/HTTP connection or command success without commandExecutor/nativeClient injection',
        'full fritzconnection live protocol implementation in dependency-free TypeScript',
        'Home Assistant image platform mapping because the current integration entity platform model has no image entity type',
      ],
    },
  };

  public async setup(configArg: IFritzConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new FritzRuntime(new FritzClient(configArg));
  }

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

export class HomeAssistantFritzIntegration extends FritzIntegration {}

class FritzRuntime implements IIntegrationRuntime {
  public domain = fritzDomain;

  constructor(private readonly client: FritzClient) {}

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

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

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

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

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