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 { AndroidIpWebcamClient } from './android_ip_webcam.classes.client.js';
import { AndroidIpWebcamConfigFlow } from './android_ip_webcam.classes.configflow.js';
import { createAndroidIpWebcamDiscoveryDescriptor } from './android_ip_webcam.discovery.js';
import { AndroidIpWebcamMapper } from './android_ip_webcam.mapper.js';
import type { IAndroidIpWebcamConfig } from './android_ip_webcam.types.js';

export class AndroidIpWebcamIntegration extends BaseIntegration<IAndroidIpWebcamConfig> {
  public readonly domain = 'android_ip_webcam';
  public readonly displayName = 'Android IP Webcam';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createAndroidIpWebcamDiscoveryDescriptor();
  public readonly configFlow = new AndroidIpWebcamConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/android_ip_webcam',
    upstreamDomain: 'android_ip_webcam',
    integrationType: 'device',
    iotClass: 'local_polling',
    requirements: ['pydroid-ipcam==3.0.0'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@engrbm87'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/android_ip_webcam',
    nativePort: {
      snapshotMapping: true,
      manualHostUrlDiscovery: true,
      liveHttpCommands: true,
      liveEvents: false,
    },
  };

  public async setup(configArg: IAndroidIpWebcamConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new AndroidIpWebcamRuntime(new AndroidIpWebcamClient(configArg));
  }

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

export class HomeAssistantAndroidIpWebcamIntegration extends AndroidIpWebcamIntegration {}

class AndroidIpWebcamRuntime implements IIntegrationRuntime {
  public domain = 'android_ip_webcam';

  constructor(private readonly client: AndroidIpWebcamClient) {}

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

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

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    try {
      const snapshot = await this.client.getSnapshot();
      const command = AndroidIpWebcamMapper.commandForService(snapshot, requestArg);
      if (!command) {
        return { success: false, error: `Unsupported Android IP Webcam 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();
  }
}
