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 { DdwrtClient } from './ddwrt.classes.client.js';
import { DdwrtConfigFlow } from './ddwrt.classes.configflow.js';
import { ddwrtDisplayName, ddwrtDomain } from './ddwrt.constants.js';
import { createDdwrtDiscoveryDescriptor } from './ddwrt.discovery.js';
import { DdwrtMapper } from './ddwrt.mapper.js';
import type { IDdwrtConfig } from './ddwrt.types.js';

export class DdwrtIntegration extends BaseIntegration<IDdwrtConfig> {
  public readonly domain = ddwrtDomain;
  public readonly displayName = ddwrtDisplayName;
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createDdwrtDiscoveryDescriptor();
  public readonly configFlow = new DdwrtConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/ddwrt',
    upstreamDomain: ddwrtDomain,
    integrationType: 'hub',
    iotClass: 'local_polling',
    qualityScale: 'legacy',
    requirements: [] as string[],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: [] as string[],
    documentation: 'https://www.home-assistant.io/integrations/ddwrt',
    configFlow: true,
    discovery: {
      dhcp: ['explicit ddwrt metadata or DD-WRT hostname/model hints'],
      http: ['Status_Wireless.live.asp / Status_Lan.live.asp live response bodies'],
      manual: true,
      note: 'Home Assistant upstream has no automatic discovery. This native port supports explicit DHCP/http/manual candidates and captured local live status snapshots.',
    },
    runtime: {
      type: 'control-runtime',
      polling: 'local DD-WRT web status pages or supplied snapshot/nativeClient/transport',
      platforms: ['sensor', 'binary_sensor', 'device_tracker-equivalent'],
      services: ['ddwrt.snapshot', 'ddwrt.status', 'ddwrt.refresh', 'ddwrt.reboot delegated only'],
    },
    localApi: {
      implemented: [
        'Config flow for host, username, password, HTTP/HTTPS, verify SSL, wireless_only, captured status data, and snapshots',
        'Native HTTP Basic Auth reads of Status_Wireless.live.asp and Status_Lan.live.asp',
        'DD-WRT live response parser for {key::value} data, active_wireless, arp_table, and dhcp_leases',
        'Snapshot-to-router sensors and device-tracker-equivalent binary sensor mapping for active clients',
        'Refresh/snapshot runtime services and delegated command execution via nativeClient, commandExecutor, or transport.execute',
      ],
      explicitUnsupported: [
        'Claiming router command success through static snapshots or native HTTP status pages',
        'Mutating DD-WRT web UI endpoints without an injected client/executor/transport',
        'Full Home Assistant device_tracker platform parity because the shared runtime entity model has no device_tracker platform',
      ],
    },
  };

  public async setup(configArg: IDdwrtConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new DdwrtRuntime(new DdwrtClient(configArg));
  }

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

export class HomeAssistantDdwrtIntegration extends DdwrtIntegration {}

class DdwrtRuntime implements IIntegrationRuntime {
  public domain = ddwrtDomain;

  constructor(private readonly client: DdwrtClient) {}

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

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

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

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

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