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 { VelbusClient } from './velbus.classes.client.js';
import { VelbusConfigFlow } from './velbus.classes.configflow.js';
import { createVelbusDiscoveryDescriptor } from './velbus.discovery.js';
import { VelbusMapper } from './velbus.mapper.js';
import type { IVelbusConfig } from './velbus.types.js';

export class VelbusIntegration extends BaseIntegration<IVelbusConfig> {
  public readonly domain = 'velbus';
  public readonly displayName = 'Velbus';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createVelbusDiscoveryDescriptor();
  public readonly configFlow = new VelbusConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/velbus',
    upstreamDomain: 'velbus',
    integrationType: 'hub',
    iotClass: 'local_push',
    qualityScale: 'silver',
    requirements: ['velbus-aio==2026.4.1'],
    dependencies: ['usb', 'file_upload'],
    afterDependencies: [],
    codeowners: ['@Cereal2nd', '@brefra'],
    configFlow: true,
    documentation: 'https://www.home-assistant.io/integrations/velbus',
    discovery: {
      manual: ['serial', 'tcp'],
      usb: [
        { vid: '10CF', pid: '0B1B' },
        { vid: '10CF', pid: '0516' },
        { vid: '10CF', pid: '0517' },
        { vid: '10CF', pid: '0518' },
      ],
      note: 'Home Assistant Velbus supports config flow for USB/serial and TCP/IP gateways; this runtime exposes manual serial/TCP discovery plus USB VID/PID matching.',
    },
    runtime: {
      type: 'control-runtime',
      mode: 'manual snapshot',
      entities: ['light', 'switch', 'sensor', 'binary_sensor', 'cover', 'climate'],
      services: ['turn_on', 'turn_off', 'set_value', 'open', 'close'],
    },
    localApi: {
      implemented: [
        'Home Assistant Velbus entity semantics from velbus-aio channel collections',
        'manual serial/TCP gateway configuration DSNs',
        'snapshot module/channel mapping',
        'manual snapshot command mutation for supported service calls',
      ],
      explicitUnsupported: [
        'live Velbus serial/CAN frame encoding and decoding',
        'live bus scan/sync_clock/set_memo_text/clear_cache services',
        'VLP file parsing',
        'firmware upgrade or module programming',
      ],
    },
  };

  public async setup(configArg: IVelbusConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new VelbusRuntime(new VelbusClient(configArg));
  }

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

export class HomeAssistantVelbusIntegration extends VelbusIntegration {}

class VelbusRuntime implements IIntegrationRuntime {
  public domain = 'velbus';

  constructor(private readonly client: VelbusClient) {}

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

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

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

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