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 { SynologySrmClient } from './synology_srm.classes.client.js';
import { SynologySrmConfigFlow } from './synology_srm.classes.configflow.js';
import { createSynologySrmDiscoveryDescriptor } from './synology_srm.discovery.js';
import { SynologySrmMapper } from './synology_srm.mapper.js';
import type { ISynologySrmConfig } from './synology_srm.types.js';
import { synologySrmDomain } from './synology_srm.types.js';

export class SynologySrmIntegration extends BaseIntegration<ISynologySrmConfig> {
  public readonly domain = synologySrmDomain;
  public readonly displayName = 'Synology SRM';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createSynologySrmDiscoveryDescriptor();
  public readonly configFlow = new SynologySrmConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/synology_srm',
    upstreamDomain: synologySrmDomain,
    integrationType: 'hub',
    iotClass: 'local_polling',
    qualityScale: 'legacy',
    requirements: ['synology-srm==0.2.0'],
    dependencies: [] as string[],
    afterDependencies: [] as string[],
    codeowners: ['@aerialls'],
    documentation: 'https://www.home-assistant.io/integrations/synology_srm',
    configFlow: true,
    runtime: {
      mode: 'native TypeScript snapshot/manual Synology SRM mapping',
      platforms: ['binary_sensor', 'button', 'sensor', 'switch', 'device_tracker-equivalent'],
      services: ['refresh', 'snapshot', 'status', 'reboot', 'block_client', 'unblock_client', 'set_client_blocked'],
    },
    localApi: {
      implemented: [
        'manual/local SRM router candidates and config flow using the Home Assistant defaults for port, SSL, username, and TLS verification',
        'snapshot/native-client mapping for router, system, network, interface, client/device-tracker, traffic, sensor, and represented switch data',
        'Home Assistant device-tracker client attribute aliases from the SRM component',
        'safe command modeling for explicitly represented router, client, and switch actions',
      ],
      explicitUnsupported: [
        'homeassistant_compat shims',
        'fake Synology SRM HTTP/API login, polling, scan, or command success without nativeClient, snapshotProvider, or commandExecutor injection',
        'full synology-srm live protocol implementation in dependency-free TypeScript',
      ],
    },
  };

  public async setup(configArg: ISynologySrmConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new SynologySrmRuntime(new SynologySrmClient(configArg));
  }

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

export class HomeAssistantSynologySrmIntegration extends SynologySrmIntegration {}

class SynologySrmRuntime implements IIntegrationRuntime {
  public domain = synologySrmDomain;

  constructor(private readonly client: SynologySrmClient) {}

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

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

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

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

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