import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import { rflinkDefaultBaudRate, rflinkDefaultReconnectInterval, rflinkDefaultTcpKeepaliveIdleTimer, rflinkDefaultWaitForAck } from './rflink.constants.js';
import type { IRflinkConfig, TRflinkConnectionType } from './rflink.types.js';

export class RflinkConfigFlow implements IConfigFlow<IRflinkConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IRflinkConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect RFLink gateway',
      description: 'Configure a local RFLink gateway. Use host and TCP port for a serial bridge, or serial port for a directly attached gateway.',
      fields: [
        { name: 'connectionType', label: 'Connection type', type: 'select', required: true, options: [{ label: 'Serial', value: 'serial' }, { label: 'TCP', value: 'tcp' }] },
        { name: 'serialPort', label: 'Serial port', type: 'text' },
        { name: 'host', label: 'TCP host', type: 'text' },
        { name: 'port', label: 'TCP port', type: 'number' },
        { name: 'baudRate', label: 'Serial baud rate', type: 'number' },
        { name: 'waitForAck', label: 'Wait for acknowledgements', type: 'boolean' },
      ],
      submit: async (valuesArg) => {
        const connectionType = this.connectionType(valuesArg.connectionType) || this.connectionType(candidateArg.metadata?.connectionType) || (candidateArg.host ? 'tcp' : 'serial');
        const serialPort = this.stringValue(valuesArg.serialPort) || this.stringValue(candidateArg.metadata?.serialPort);
        const host = this.stringValue(valuesArg.host) || candidateArg.host;
        const port = this.numberValue(valuesArg.port) || candidateArg.port;

        if (connectionType === 'tcp' && (!host || !port)) {
          return { kind: 'error', title: 'RFLink configuration failed', error: 'TCP RFLink setup requires host and port.' };
        }
        if (connectionType === 'serial' && !serialPort) {
          return { kind: 'error', title: 'RFLink configuration failed', error: 'Serial RFLink setup requires a serial port path.' };
        }

        return {
          kind: 'done',
          title: 'RFLink gateway configured',
          config: {
            connectionType,
            host: connectionType === 'tcp' ? host : undefined,
            port: connectionType === 'tcp' ? port : serialPort,
            baudRate: this.numberValue(valuesArg.baudRate) || this.numberValue(candidateArg.metadata?.baudRate) || rflinkDefaultBaudRate,
            waitForAck: this.booleanValue(valuesArg.waitForAck) ?? rflinkDefaultWaitForAck,
            tcpKeepaliveIdleTimer: rflinkDefaultTcpKeepaliveIdleTimer,
            reconnectInterval: rflinkDefaultReconnectInterval,
            gateway: {
              id: candidateArg.id || host || serialPort,
              name: candidateArg.name || 'RFLink Gateway',
              connectionType,
              host: connectionType === 'tcp' ? host : undefined,
              port: connectionType === 'tcp' ? port : serialPort,
              baudRate: this.numberValue(valuesArg.baudRate) || this.numberValue(candidateArg.metadata?.baudRate) || rflinkDefaultBaudRate,
            },
          },
        };
      },
    };
  }

  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;
  }

  private booleanValue(valueArg: unknown): boolean | undefined {
    return typeof valueArg === 'boolean' ? valueArg : undefined;
  }

  private connectionType(valueArg: unknown): TRflinkConnectionType | undefined {
    return valueArg === 'serial' || valueArg === 'tcp' || valueArg === 'manual' ? valueArg : undefined;
  }
}
