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 { CiscoIosClient } from './cisco_ios.classes.client.js';
import { CiscoIosConfigFlow } from './cisco_ios.classes.configflow.js';
import { ciscoIosDefaultArpCommand, ciscoIosDefaultTerminalLengthCommand, ciscoIosDisplayName, ciscoIosDomain } from './cisco_ios.constants.js';
import { createCiscoIosDiscoveryDescriptor } from './cisco_ios.discovery.js';
import { CiscoIosMapper } from './cisco_ios.mapper.js';
import type { ICiscoIosConfig } from './cisco_ios.types.js';

export class CiscoIosIntegration extends BaseIntegration<ICiscoIosConfig> {
  public readonly domain = ciscoIosDomain;
  public readonly displayName = ciscoIosDisplayName;
  public readonly status = 'read-only-runtime' as const;
  public readonly discoveryDescriptor = createCiscoIosDiscoveryDescriptor();
  public readonly configFlow = new CiscoIosConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/cisco_ios',
    upstreamDomain: ciscoIosDomain,
    integrationType: 'hub',
    iotClass: 'local_polling',
    qualityScale: 'legacy',
    requirements: ['pexpect==4.9.0'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@fbradyirl'],
    documentation: 'https://www.home-assistant.io/integrations/cisco_ios',
    configFlow: true,
    discovery: {
      manual: true,
      dhcp: ['explicit cisco_ios metadata only'],
      note: 'Home Assistant does not declare automatic discovery for cisco_ios. This native port supports conservative explicit DHCP candidates and manual setup with host, snapshot, or show ip arp output.',
    },
    runtime: {
      type: 'read-only-runtime',
      polling: `manual Cisco IOS CLI snapshot data or injected executor/client/transport running "${ciscoIosDefaultTerminalLengthCommand}" and "${ciscoIosDefaultArpCommand}"`,
      platforms: ['binary_sensor', 'sensor'],
      services: ['cisco_ios.snapshot', 'cisco_ios.refresh', 'cisco_ios.show_ip_arp', 'cisco_ios.run_command'],
    },
    localApi: {
      implemented: [
        'Manual Cisco IOS setup candidates and config flow for SSH host metadata, snapshot JSON, and show ip arp output',
        'Cisco IOS ARP table parser compatible with Home Assistant cisco_ios presence rule: numeric age less than one minute is present',
        'Snapshot-to-device/entity mapper for router connectivity, ARP entry count, tracked device count, and tracked MAC presence',
        'Runtime snapshot/refresh through injected nativeClient, commandExecutor, or transport only',
      ],
      explicitUnsupported: [
        'Direct pxssh/native SSH implementation in this dependency-free TypeScript port',
        'Claiming live CLI command success without nativeClient, commandExecutor, or transport.execute',
        'Cisco IOS write/control services; upstream Home Assistant cisco_ios is a legacy read-only device_tracker scanner',
      ],
    },
  };

  public async setup(configArg: ICiscoIosConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new CiscoIosRuntime(new CiscoIosClient(configArg));
  }

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

export class HomeAssistantCiscoIosIntegration extends CiscoIosIntegration {}

class CiscoIosRuntime implements IIntegrationRuntime {
  public domain = ciscoIosDomain;

  constructor(private readonly client: CiscoIosClient) {}

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

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

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

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

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