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 { MotionEyeClient } from './motioneye.classes.client.js';
import { MotionEyeConfigFlow } from './motioneye.classes.configflow.js';
import { createMotionEyeDiscoveryDescriptor } from './motioneye.discovery.js';
import { MotionEyeMapper } from './motioneye.mapper.js';
import type { IMotionEyeConfig } from './motioneye.types.js';

export class MotionEyeIntegration extends BaseIntegration<IMotionEyeConfig> {
  public readonly domain = 'motioneye';
  public readonly displayName = 'motionEye';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createMotionEyeDiscoveryDescriptor();
  public readonly configFlow = new MotionEyeConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/motioneye',
    upstreamDomain: 'motioneye',
    integrationType: 'hub',
    iotClass: 'local_polling',
    requirements: ['motioneye-client==0.3.14'],
    dependencies: ['http', 'webhook'],
    afterDependencies: ['media_source'],
    codeowners: ['@dermotduffy'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/motioneye',
    nativePort: {
      snapshotMapping: true,
      manualUrlDiscovery: true,
      liveHttpCommands: true,
      liveEvents: false,
      homeAssistantCompat: false,
    },
  };

  public async setup(configArg: IMotionEyeConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new MotionEyeRuntime(new MotionEyeClient(configArg));
  }

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

export class HomeAssistantMotioneyeIntegration extends MotionEyeIntegration {}
export class HomeAssistantMotionEyeIntegration extends MotionEyeIntegration {}

class MotionEyeRuntime implements IIntegrationRuntime {
  public domain = 'motioneye';

  constructor(private readonly client: MotionEyeClient) {}

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

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

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