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 { MikrotikClient } from './mikrotik.classes.client.js';
import { MikrotikConfigFlow } from './mikrotik.classes.configflow.js';
import { createMikrotikDiscoveryDescriptor } from './mikrotik.discovery.js';
import { MikrotikMapper } from './mikrotik.mapper.js';
import type { IMikrotikConfig } from './mikrotik.types.js';
import { mikrotikDomain } from './mikrotik.types.js';

export class MikrotikIntegration extends BaseIntegration<IMikrotikConfig> {
  public readonly domain = mikrotikDomain;
  public readonly displayName = 'Mikrotik';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createMikrotikDiscoveryDescriptor();
  public readonly configFlow = new MikrotikConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/mikrotik',
    upstreamDomain: mikrotikDomain,
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['librouteros==3.2.0'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@engrbm87'],
    documentation: 'https://www.home-assistant.io/integrations/mikrotik',
    configFlow: true,
    runtime: {
      mode: 'native TypeScript snapshot/manual RouterOS/API mapping',
      platforms: ['device_tracker', 'binary_sensor', 'sensor', 'switch', 'button'],
      services: ['refresh', 'snapshot', 'status', 'reboot', 'arp_ping', 'disconnect_client', 'enable_interface', 'disable_interface'],
    },
    localApi: {
      implemented: [
        'manual Mikrotik RouterOS/API setup candidates and config flow',
        'snapshot mapping for router resources, device-tracker equivalents, interfaces, clients, traffic counters/rates, and represented interface/client/router controls',
        'safe RouterOS/API command modeling for explicitly represented reboot, ARP ping, client disconnect, and interface enablement actions',
      ],
      explicitUnsupported: [
        'homeassistant_compat shims',
        'fake RouterOS/API connection or command success without commandExecutor/nativeClient injection',
        'full librouteros live protocol implementation in dependency-free TypeScript',
      ],
    },
  };

  public async setup(configArg: IMikrotikConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new MikrotikRuntime(new MikrotikClient(configArg));
  }

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

export class HomeAssistantMikrotikIntegration extends MikrotikIntegration {}

class MikrotikRuntime implements IIntegrationRuntime {
  public domain = mikrotikDomain;

  constructor(private readonly client: MikrotikClient) {}

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

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

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

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

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