import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { ISqueezeboxConfig } from './squeezebox.types.js';
import { squeezeboxDefaultBrowseLimit, squeezeboxDefaultHttpPort, squeezeboxDefaultTimeoutMs, squeezeboxDefaultVolumeStep } from './squeezebox.types.js';

export class SqueezeboxConfigFlow implements IConfigFlow<ISqueezeboxConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<ISqueezeboxConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Lyrion Music Server',
      description: 'Configure a local Logitech/Lyrion Media Server HTTP JSON-RPC endpoint.',
      fields: [
        { name: 'host', label: 'LMS host', type: 'text', required: true },
        { name: 'port', label: 'HTTP port', type: 'number' },
        { name: 'https', label: 'Use HTTPS', type: 'boolean' },
        { name: 'username', label: 'Username', type: 'text' },
        { name: 'password', label: 'Password', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'browseLimit', label: 'Browse limit', type: 'number' },
        { name: 'volumeStep', label: 'Volume step percent', type: 'number' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host || '';
        if (!host) {
          return { kind: 'error', title: 'Squeezebox setup failed', error: 'Lyrion Music Server host is required.' };
        }
        const port = this.numberValue(valuesArg.port) || candidateArg.port || squeezeboxDefaultHttpPort;
        return {
          kind: 'done',
          title: 'Squeezebox configured',
          config: {
            host,
            port,
            https: this.booleanValue(valuesArg.https),
            username: this.stringValue(valuesArg.username),
            password: this.stringValue(valuesArg.password),
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            serverId: candidateArg.id || `${host}:${port}`,
            timeoutMs: squeezeboxDefaultTimeoutMs,
            browseLimit: this.numberValue(valuesArg.browseLimit) || squeezeboxDefaultBrowseLimit,
            volumeStep: this.numberValue(valuesArg.volumeStep) || squeezeboxDefaultVolumeStep,
            transport: 'jsonrpc',
          },
        };
      },
    };
  }

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

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