import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IBluesoundConfig } from './bluesound.types.js';
import { bluesoundDefaultPort, bluesoundDefaultTimeoutMs } from './bluesound.types.js';

export class BluesoundConfigFlow implements IConfigFlow<IBluesoundConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IBluesoundConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Bluesound',
      description: candidateArg.source === 'manual'
        ? 'Configure a local Bluesound/BluOS player HTTP endpoint.'
        : 'Confirm or adjust the discovered local Bluesound/BluOS player.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host || '';
        if (!host) {
          return { kind: 'error', title: 'Bluesound setup failed', error: 'Bluesound setup requires a host.' };
        }
        const port = this.numberValue(valuesArg.port) || candidateArg.port || bluesoundDefaultPort;
        return {
          kind: 'done',
          title: 'Bluesound configured',
          config: {
            host,
            port,
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            macAddress: candidateArg.macAddress,
            manufacturer: candidateArg.manufacturer,
            model: candidateArg.model,
            timeoutMs: bluesoundDefaultTimeoutMs,
          },
        };
      },
    };
  }

  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) && valueArg > 0) {
      return Math.round(valueArg);
    }
    if (typeof valueArg === 'string' && valueArg.trim()) {
      const parsed = Number(valueArg);
      return Number.isFinite(parsed) && parsed > 0 ? Math.round(parsed) : undefined;
    }
    return undefined;
  }
}
