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 { HikvisionClient } from './hikvision.classes.client.js';
import { HikvisionConfigFlow } from './hikvision.classes.configflow.js';
import { createHikvisionDiscoveryDescriptor } from './hikvision.discovery.js';
import { HikvisionMapper } from './hikvision.mapper.js';
import type { IHikvisionConfig } from './hikvision.types.js';

export class HikvisionIntegration extends BaseIntegration<IHikvisionConfig> {
  public readonly domain = 'hikvision';
  public readonly displayName = 'Hikvision';
  public readonly status = 'read-only-runtime' as const;
  public readonly discoveryDescriptor = createHikvisionDiscoveryDescriptor();
  public readonly configFlow = new HikvisionConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/hikvision',
    upstreamDomain: 'hikvision',
    integrationType: 'device',
    iotClass: 'local_push',
    requirements: ['pyHik==0.4.2'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@mezz64', '@ptarjan'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/hikvision',
    nativePort: {
      manualLocalDiscovery: true,
      isapiSnapshotMapping: true,
      nvrChannels: true,
      binarySensorEventMapping: true,
      lineCrossing: true,
      fieldDetection: true,
      liveEventStream: false,
      liveWritableCommands: false,
    },
  };

  public async setup(configArg: IHikvisionConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new HikvisionRuntime(new HikvisionClient(configArg));
  }

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

export class HomeAssistantHikvisionIntegration extends HikvisionIntegration {}

class HikvisionRuntime implements IIntegrationRuntime {
  public domain = 'hikvision';

  constructor(private readonly client: HikvisionClient) {}

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

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

  public async subscribe(handlerArg: (eventArg: IIntegrationEvent) => void): Promise<() => Promise<void>> {
    void handlerArg;
    throw new Error('Hikvision live event streaming is not implemented in this TypeScript port; use snapshot/manual event data or poll entities.');
  }

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