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 { ModbusClient } from './modbus.classes.client.js';
import { ModbusConfigFlow } from './modbus.classes.configflow.js';
import { createModbusDiscoveryDescriptor } from './modbus.discovery.js';
import { ModbusMapper } from './modbus.mapper.js';
import type { IModbusConfig } from './modbus.types.js';

export class ModbusIntegration extends BaseIntegration<IModbusConfig> {
  public readonly domain = 'modbus';
  public readonly displayName = 'Modbus';
  public readonly status = 'control-runtime' as const;
  public readonly discoveryDescriptor = createModbusDiscoveryDescriptor();
  public readonly configFlow = new ModbusConfigFlow();
  public readonly metadata = {
    source: 'home-assistant/core',
    upstreamPath: 'homeassistant/components/modbus',
    upstreamDomain: 'modbus',
    iotClass: 'local_polling',
    requirements: ['pymodbus==3.11.2'],
    dependencies: [],
    afterDependencies: [],
    codeowners: [],
    documentation: 'https://www.home-assistant.io/integrations/modbus',
    configFlow: true,
    discovery: {
      manual: true,
      tcp: true,
      serial: false,
      note: 'Manual Modbus TCP setup is implemented. Serial RTU ports are not guessed or probed.',
    },
    runtime: {
      type: 'control-runtime',
      polling: 'local snapshot or explicit Modbus TCP requests',
      services: ['read_coil', 'read_register', 'write_coil', 'write_register', 'stop', 'restart', 'refresh'],
    },
    localApi: {
      implemented: [
        'manual Modbus TCP hub configuration',
        'snapshot/manual configured registers and coils',
        'Modbus TCP MBAP request shape for read coils, read discrete inputs, read holding/input registers, write coil(s), and write register(s)',
        'register/coils mapping to sensor, binary_sensor, switch, and number entities',
      ],
      explicitUnsupported: [
        'unsafe serial RTU discovery or serial port guessing',
        'serial RTU runtime transport',
        'RTU-over-TCP framer runtime transport',
        'UDP runtime transport',
        'climate, cover, fan, and light platform behavior beyond configured register/coil entities',
      ],
    },
  };

  public async setup(configArg: IModbusConfig, contextArg: IIntegrationSetupContext): Promise<IIntegrationRuntime> {
    void contextArg;
    return new ModbusRuntime(new ModbusClient(configArg));
  }

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

export class HomeAssistantModbusIntegration extends ModbusIntegration {}

class ModbusRuntime implements IIntegrationRuntime {
  public domain = 'modbus';

  constructor(private readonly client: ModbusClient) {}

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

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

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

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