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 { AsuswrtClient } from './asuswrt.classes.client.js';
import { AsuswrtConfigFlow } from './asuswrt.classes.configflow.js';
import { createAsuswrtDiscoveryDescriptor } from './asuswrt.discovery.js';
import { AsuswrtMapper } from './asuswrt.mapper.js';
import type { IAsuswrtConfig } from './asuswrt.types.js';
import { asuswrtDomain } from './asuswrt.types.js';

export class AsuswrtIntegration extends BaseIntegration<IAsuswrtConfig> {
  public readonly domain = asuswrtDomain;
  public readonly displayName = 'ASUSWRT';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createAsuswrtDiscoveryDescriptor();
  public readonly configFlow = new AsuswrtConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/asuswrt',
    upstreamDomain: asuswrtDomain,
    integrationType: 'hub',
    iotClass: 'local_polling',
    requirements: ['aioasuswrt==1.5.4', 'asusrouter==1.21.3'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@kennedyshead', '@ollo69', '@Vaskivskyi'],
    documentation: 'https://www.home-assistant.io/integrations/asuswrt',
    configFlow: true,
    runtime: {
      mode: 'native TypeScript snapshot/manual router mapping',
      platforms: ['sensor', 'binary_sensor', 'button'],
      services: ['refresh', 'snapshot', 'reboot', 'reconnect_device', 'disconnect_device', 'block_device', 'unblock_device'],
    },
    localApi: {
      implemented: [
        'manual ASUSWRT router setup candidates and config flow',
        'snapshot mapping for router sensors, device tracker presence, interfaces, traffic counters/rates, CPU, memory, temperatures, uptime, and load average',
        'safe command modeling for explicitly declared router reboot and connected-device actions',
      ],
      explicitUnsupported: [
        'homeassistant_compat shims',
        'fake SSH/Telnet connection or command success without commandExecutor/nativeClient injection',
        'full asusrouter/aioasuswrt live protocol implementation in dependency-free TypeScript',
      ],
    },
  };

  public async setup(configArg: IAsuswrtConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new AsuswrtRuntime(new AsuswrtClient(configArg));
  }

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

export class HomeAssistantAsuswrtIntegration extends AsuswrtIntegration {}

class AsuswrtRuntime implements IIntegrationRuntime {
  public domain = asuswrtDomain;

  constructor(private readonly client: AsuswrtClient) {}

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

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

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

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

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