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 { AmcrestClient } from './amcrest.classes.client.js';
import { AmcrestConfigFlow } from './amcrest.classes.configflow.js';
import { createAmcrestDiscoveryDescriptor } from './amcrest.discovery.js';
import { AmcrestMapper } from './amcrest.mapper.js';
import type { IAmcrestConfig } from './amcrest.types.js';

export class AmcrestIntegration extends BaseIntegration<IAmcrestConfig> {
  public readonly domain = 'amcrest';
  public readonly displayName = 'Amcrest';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createAmcrestDiscoveryDescriptor();
  public readonly configFlow = new AmcrestConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/amcrest',
    upstreamDomain: 'amcrest',
    integrationType: 'device',
    iotClass: 'local_polling',
    qualityScale: 'legacy',
    requirements: ['amcrest==1.9.9'],
    dependencies: ['ffmpeg'],
    afterDependencies: [],
    codeowners: ['@flacjacket'],
    documentation: 'https://www.home-assistant.io/integrations/amcrest',
    nativePort: {
      manualLocalDiscovery: true,
      snapshotMapping: true,
      liveHttpCgiCommands: true,
      liveEvents: false,
      rtspProxying: false,
      ffmpegProxying: false,
    },
  };

  public async setup(configArg: IAmcrestConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new AmcrestRuntime(new AmcrestClient(configArg));
  }

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

export class HomeAssistantAmcrestIntegration extends AmcrestIntegration {}

class AmcrestRuntime implements IIntegrationRuntime {
  public domain = 'amcrest';

  constructor(private readonly client: AmcrestClient) {}

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

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

  public async subscribe(handlerArg: (eventArg: IIntegrationEvent) => void): Promise<() => Promise<void>> {
    void handlerArg;
    throw new Error('Amcrest live event streaming is not implemented in this TypeScript port; use polled binary sensors or refresh snapshots.');
  }

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