import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IEsphomeConfig } from './esphome.types.js';
import { esphomeDefaultNativeApiPort } from './esphome.types.js';

export class EsphomeConfigFlow implements IConfigFlow<IEsphomeConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IEsphomeConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect ESPHome',
      description: 'Configure an ESPHome native API device. Snapshot/manual data is supported; live protobuf control is reported explicitly if unavailable.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Native API port', type: 'number' },
        { name: 'encryptionKey', label: 'Encryption key', type: 'password' },
        { name: 'password', label: 'Legacy API password', type: 'password' },
      ],
      submit: async (valuesArg) => ({
        kind: 'done',
        title: 'ESPHome configured',
        config: {
          host: this.stringValue(valuesArg.host) || candidateArg.host || '',
          port: this.numberValue(valuesArg.port) || candidateArg.port || esphomeDefaultNativeApiPort,
          name: candidateArg.name,
          deviceName: this.stringValue(candidateArg.metadata?.deviceName),
          encryptionKey: this.stringValue(valuesArg.encryptionKey) || this.stringValue(candidateArg.metadata?.encryptionKey),
          noisePsk: this.stringValue(candidateArg.metadata?.noisePsk),
          password: this.stringValue(valuesArg.password) || this.stringValue(candidateArg.metadata?.password),
          deviceInfo: {
            name: this.stringValue(candidateArg.metadata?.deviceName) || candidateArg.name,
            friendlyName: candidateArg.name,
            macAddress: candidateArg.macAddress,
            manufacturer: candidateArg.manufacturer,
            model: candidateArg.model,
            host: candidateArg.host,
            port: candidateArg.port || esphomeDefaultNativeApiPort,
            apiEncryptionSupported: Boolean(candidateArg.metadata?.encryptionRequired),
          },
        },
      }),
    };
  }

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