import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { ICastConfig } from './cast.types.js';

export class CastConfigFlow implements IConfigFlow<ICastConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<ICastConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Google Cast',
      description: 'Configure Google Cast mDNS discovery and optional known hosts.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: false },
        { name: 'port', label: 'Cast port', type: 'number' },
        { name: 'httpPort', label: 'HTTP info port', type: 'number' },
        { name: 'knownHosts', label: 'Known hosts, comma separated', type: 'text' },
        { name: 'uuid', label: 'Allowed UUID', type: 'text' },
      ],
      submit: async (valuesArg) => ({
        kind: 'done',
        title: 'Google Cast configured',
        config: {
          host: this.stringValue(valuesArg.host) || candidateArg.host,
          port: this.numberValue(valuesArg.port) || candidateArg.port || 8009,
          httpPort: this.numberValue(valuesArg.httpPort) || 8008,
          knownHosts: this.listValue(valuesArg.knownHosts),
          uuid: this.stringValue(valuesArg.uuid) || candidateArg.id,
        },
      }),
    };
  }

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

  private listValue(valueArg: unknown): string[] {
    if (Array.isArray(valueArg)) {
      return valueArg.filter((itemArg): itemArg is string => typeof itemArg === 'string' && Boolean(itemArg.trim())).map((itemArg) => itemArg.trim());
    }
    if (typeof valueArg !== 'string') {
      return [];
    }
    return valueArg.split(',').map((itemArg) => itemArg.trim()).filter(Boolean);
  }
}
