import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IMpdConfig } from './mpd.types.js';
import { mpdDefaultPort } from './mpd.types.js';

const defaultTimeoutMs = 5000;

export class MpdConfigFlow implements IConfigFlow<IMpdConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IMpdConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Music Player Daemon',
      description: 'Configure the local MPD TCP control endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'TCP port', type: 'number' },
        { name: 'password', label: 'Password', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host || '';
        if (!host) {
          return { kind: 'error', title: 'MPD setup failed', error: 'MPD host is required.' };
        }
        const port = this.numberValue(valuesArg.port) || candidateArg.port || mpdDefaultPort;
        return {
          kind: 'done',
          title: 'MPD configured',
          config: {
            host,
            port,
            password: this.stringValue(valuesArg.password),
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            serverId: candidateArg.id || `${host}:${port}`,
            transport: 'tcp',
            timeoutMs: defaultTimeoutMs,
          },
        };
      },
    };
  }

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