import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import { homematicDefaultInterfacePort, homematicDefaultJsonPort, type IHomematicConfig } from './homematic.types.js';

export class HomematicConfigFlow implements IConfigFlow<IHomematicConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IHomematicConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Homematic CCU',
      description: 'Configure the local Homematic XML-RPC interface. Live callback event server registration is not part of this runtime.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'XML-RPC port', type: 'number', required: false },
        { name: 'interfaceName', label: 'Interface name', type: 'text', required: false },
        { name: 'username', label: 'Username', type: 'text', required: false },
        { name: 'password', label: 'Password', type: 'password', required: false },
        { name: 'ssl', label: 'Use HTTPS', type: 'boolean', required: false },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host || '';
        const port = this.numberValue(valuesArg.port) || candidateArg.port || homematicDefaultInterfacePort;
        const interfaceName = this.stringValue(valuesArg.interfaceName) || this.stringValue(candidateArg.metadata?.interfaceName) || 'default';
        const ssl = this.booleanValue(valuesArg.ssl) ?? this.booleanValue(candidateArg.metadata?.ssl) ?? false;
        return {
          kind: 'done',
          title: 'Homematic CCU configured',
          config: {
            host,
            port,
            ssl,
            username: this.stringValue(valuesArg.username),
            password: this.stringValue(valuesArg.password),
            interfaceName,
            uniqueId: candidateArg.id || candidateArg.serialNumber || candidateArg.macAddress || host,
            name: candidateArg.name || 'Homematic CCU',
            jsonPort: homematicDefaultJsonPort,
            interfaces: {
              [interfaceName]: {
                name: interfaceName,
                host,
                port,
                ssl,
                username: this.stringValue(valuesArg.username),
                password: this.stringValue(valuesArg.password),
                jsonPort: homematicDefaultJsonPort,
                connect: true,
              },
            },
          },
        };
      },
    };
  }

  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 {
    if (typeof valueArg === 'boolean') {
      return valueArg;
    }
    if (typeof valueArg === 'string') {
      const normalized = valueArg.trim().toLowerCase();
      if (['true', '1', 'yes', 'on'].includes(normalized)) {
        return true;
      }
      if (['false', '0', 'no', 'off'].includes(normalized)) {
        return false;
      }
    }
    return undefined;
  }
}
