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 { OnvifClient } from './onvif.classes.client.js';
import { OnvifConfigFlow } from './onvif.classes.configflow.js';
import { createOnvifDiscoveryDescriptor } from './onvif.discovery.js';
import { OnvifMapper } from './onvif.mapper.js';
import type { IOnvifConfig } from './onvif.types.js';

export class OnvifIntegration extends BaseIntegration<IOnvifConfig> {
  public readonly domain = 'onvif';
  public readonly displayName = 'ONVIF';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createOnvifDiscoveryDescriptor();
  public readonly configFlow = new OnvifConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/onvif',
    upstreamDomain: 'onvif',
    integrationType: 'device',
    iotClass: 'local_push',
    requirements: ['onvif-zeep-async==4.0.4', 'onvif_parsers==2.3.0', 'WSDiscovery==2.1.2'],
    dependencies: ['ffmpeg'],
    afterDependencies: [],
    codeowners: ['@jterrace'],
    documentation: 'https://www.home-assistant.io/integrations/onvif',
    discovery: {
      wsDiscovery: {
        type: 'dn:NetworkVideoTransmitter',
        scope: 'onvif://www.onvif.org/Profile/Streaming',
      },
      mdns: ['_onvif._tcp.local.'],
    },
    nativePort: {
      snapshotMapping: true,
      basicSoapProbe: true,
      livePtz: false,
      liveEvents: false,
    },
  };

  public async setup(configArg: IOnvifConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new OnvifIntegrationRuntime(new OnvifClient(configArg));
  }

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

export class HomeAssistantOnvifIntegration extends OnvifIntegration {}

class OnvifIntegrationRuntime implements IIntegrationRuntime {
  public domain = 'onvif';

  constructor(private readonly client: OnvifClient) {}

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

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const snapshot = await this.client.getSnapshot();
    const command = OnvifMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `ONVIF service ${requestArg.domain}.${requestArg.service} has no native mapping.` };
    }
    try {
      const data = await this.client.execute(command);
      return { success: true, data };
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : String(error) };
    }
  }

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