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 { HomematicClient } from './homematic.classes.client.js';
import { HomematicConfigFlow } from './homematic.classes.configflow.js';
import { createHomematicDiscoveryDescriptor } from './homematic.discovery.js';
import { HomematicMapper } from './homematic.mapper.js';
import type { IHomematicConfig } from './homematic.types.js';

export class HomematicIntegration extends BaseIntegration<IHomematicConfig> {
  public readonly domain = 'homematic';
  public readonly displayName = 'Homematic';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createHomematicDiscoveryDescriptor();
  public readonly configFlow = new HomematicConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/homematic',
    upstreamDomain: 'homematic',
    integrationType: 'hub',
    iotClass: 'local_push',
    qualityScale: 'legacy',
    requirements: ['pyhomematic==0.1.77'],
    dependencies: [],
    afterDependencies: [],
    codeowners: ['@pvizeli'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/homematic',
    discovery: {
      manual: true,
      metadata: true,
      dhcp: false,
      mdns: false,
      note: 'Home Assistant Homematic is YAML/manual XML-RPC configuration; this runtime provides manual and metadata discovery only.',
    },
    runtime: {
      type: 'control-runtime',
      polling: 'snapshot/manual or XML-RPC snapshot when a host is configured',
      services: ['set_value', 'press', 'turn_on', 'turn_off', 'open', 'close', 'stop', 'set_temperature', 'raw_xmlrpc', 'refresh'],
      eventServer: 'unsupported; subscribe emits local command/runtime events only',
    },
    localApi: {
      implemented: [
        'manual/snapshot CCU interface/device/channel/datapoint state',
        'XML-RPC methodCall encoding for setValue and raw calls',
        'XML-RPC listDevices/getParamset/getParamsetDescription snapshot best effort',
        'Home Assistant-style set_device_value/virtualkey service aliases',
      ],
      explicitUnsupported: [
        'live XML-RPC callback/event server registration via init()',
        'BidCos BIN-RPC binary transport',
        'CCU JSON-RPC authentication/session flows for variables and names',
        'automatic zeroconf/dhcp discovery',
      ],
    },
  };

  public async setup(configArg: IHomematicConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new HomematicRuntime(new HomematicClient(configArg));
  }

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

export class HomeAssistantHomematicIntegration extends HomematicIntegration {}

class HomematicRuntime implements IIntegrationRuntime {
  public domain = 'homematic';

  constructor(private readonly client: HomematicClient) {}

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

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

  public async subscribe(handlerArg: (eventArg: IIntegrationEvent) => void): Promise<() => Promise<void>> {
    const unsubscribe = this.client.onEvent((eventArg) => handlerArg(HomematicMapper.toIntegrationEvent(eventArg)));
    return async () => unsubscribe();
  }

  public async callService(requestArg: IServiceCallRequest): Promise<IServiceCallResult> {
    const snapshot = await this.client.getSnapshot();
    const command = HomematicMapper.commandForService(snapshot, requestArg);
    if (!command) {
      return { success: false, error: `Unsupported Homematic service: ${requestArg.domain}.${requestArg.service}` };
    }
    const result = await this.client.sendCommand(command);
    return { success: result.success, error: result.error, data: result.data };
  }

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