import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IModbusConfig } from './modbus.types.js';

const defaultModbusTcpPort = 502;

export class ModbusConfigFlow implements IConfigFlow<IModbusConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IModbusConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Modbus TCP hub',
      description: 'Configure a known Modbus TCP endpoint. Serial RTU ports are intentionally not guessed or probed.',
      fields: [
        { name: 'name', label: 'Hub name', type: 'text', required: false },
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'TCP port', type: 'number', required: false },
        { name: 'unitId', label: 'Default unit ID', type: 'number', required: false },
        { name: 'timeoutMs', label: 'Timeout milliseconds', type: 'number', required: false },
      ],
      submit: async (valuesArg) => {
        const unitId = this.numberValue(valuesArg.unitId) || this.numberValue(candidateArg.metadata?.unitId) || 1;
        const port = this.numberValue(valuesArg.port) || candidateArg.port || defaultModbusTcpPort;
        return {
          kind: 'done',
          title: 'Modbus TCP hub configured',
          config: {
            hubs: [{
              id: candidateArg.id,
              name: this.stringValue(valuesArg.name) || candidateArg.name || 'modbus_hub',
              type: 'tcp',
              host: this.stringValue(valuesArg.host) || candidateArg.host || '',
              port,
              timeoutMs: this.numberValue(valuesArg.timeoutMs) || 5000,
              slave: unitId,
              manufacturer: candidateArg.manufacturer,
              model: candidateArg.model,
              serialNumber: candidateArg.serialNumber,
            }],
          },
        };
      },
    };
  }

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;
  }

  private numberValue(valueArg: unknown): number | undefined {
    return typeof valueArg === 'number' && Number.isFinite(valueArg) ? valueArg : typeof valueArg === 'string' && valueArg.trim() && Number.isFinite(Number(valueArg)) ? Number(valueArg) : undefined;
  }
}
