import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IMadvrConfig } from './madvr.types.js';
import { madvrDefaultPort } from './madvr.types.js';

export class MadvrConfigFlow implements IConfigFlow<IMadvrConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IMadvrConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect madVR Envy',
      description: 'Configure the local madVR Envy TCP endpoint. Live control uses validated madVR IP-control commands; Wake-on-LAN requires a MAC address.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'TCP port', type: 'number' },
        { name: 'macAddress', label: 'MAC address', type: 'text' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'model', label: 'Model', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host;
        if (!host) {
          return { kind: 'error', error: 'madVR Envy host is required.' };
        }
        return {
          kind: 'done',
          title: 'madVR Envy configured',
          config: {
            host,
            port: this.numberValue(valuesArg.port) || candidateArg.port || madvrDefaultPort,
            name: this.stringValue(valuesArg.name) || candidateArg.name || 'madVR Envy',
            model: this.stringValue(valuesArg.model) || candidateArg.model || 'Envy',
            manufacturer: candidateArg.manufacturer || 'madVR',
            macAddress: this.stringValue(valuesArg.macAddress) || candidateArg.macAddress || this.stringMetadata(candidateArg, 'macAddress'),
            serialNumber: candidateArg.serialNumber,
          },
        };
      },
    };
  }

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

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

  private stringMetadata(candidateArg: IDiscoveryCandidate, keyArg: string): string | undefined {
    const value = candidateArg.metadata?.[keyArg];
    return typeof value === 'string' && value.trim() ? value.trim() : undefined;
  }
}
