import type * as shxInterfaces from '@smarthome.exchange/interfaces';
import { BaseIntegration } from '../../core/classes.baseintegration.js';
import type { IIntegrationEntity, IIntegrationRuntime, IIntegrationSetupContext, IServiceCallRequest, IServiceCallResult } from '../../core/types.js';
import { Go2rtcClient } from './go2rtc.classes.client.js';
import { Go2rtcConfigFlow } from './go2rtc.classes.configflow.js';
import { createGo2rtcDiscoveryDescriptor } from './go2rtc.discovery.js';
import { Go2rtcMapper } from './go2rtc.mapper.js';
import type { IGo2rtcConfig } from './go2rtc.types.js';

export class Go2rtcIntegration extends BaseIntegration<IGo2rtcConfig> {
  public readonly domain = 'go2rtc';
  public readonly displayName = 'go2rtc';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createGo2rtcDiscoveryDescriptor();
  public readonly configFlow = new Go2rtcConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/go2rtc',
    upstreamDomain: 'go2rtc',
    integrationType: 'system',
    iotClass: 'local_polling',
    qualityScale: 'internal',
    requirements: ['go2rtc-client==0.4.0'],
    dependencies: ['camera'],
    afterDependencies: [],
    codeowners: ['@home-assistant/core'],
    documentation: 'https://www.home-assistant.io/integrations/go2rtc',
    nativePort: {
      snapshotMapping: true,
      manualHttpDiscovery: true,
      configFlow: true,
      liveHttpCommands: true,
      webRtcProviderModelled: true,
      managedServerProcess: false,
      homeAssistantCompat: false,
    },
  };

  public async setup(configArg: IGo2rtcConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new Go2rtcRuntime(new Go2rtcClient(configArg));
  }

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

export class HomeAssistantGo2rtcIntegration extends Go2rtcIntegration {}
export class HomeAssistantGo2RtcIntegration extends Go2rtcIntegration {}

class Go2rtcRuntime implements IIntegrationRuntime {
  public domain = 'go2rtc';

  constructor(private readonly client: Go2rtcClient) {}

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

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

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

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