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

const defaultPort = 8080;
const defaultWsPort = 9090;
const defaultTimeoutMs = 5000;

export class KodiConfigFlow implements IConfigFlow<IKodiConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IKodiConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Kodi',
      description: 'Configure the local Kodi JSON-RPC endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'HTTP JSON-RPC port', type: 'number' },
        { name: 'ssl', label: 'Use HTTPS', type: 'boolean' },
        { name: 'wsPort', label: 'WebSocket port', type: 'number' },
        { name: 'username', label: 'Username', type: 'text' },
        { name: 'password', label: 'Password', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => ({
        kind: 'done',
        title: 'Kodi configured',
        config: {
          host: this.stringValue(valuesArg.host) || candidateArg.host || '',
          port: this.numberValue(valuesArg.port) || candidateArg.port || defaultPort,
          wsPort: this.numberValue(valuesArg.wsPort) || this.numberMetadata(candidateArg, 'wsPort') || defaultWsPort,
          ssl: this.booleanValue(valuesArg.ssl) ?? this.booleanMetadata(candidateArg, 'ssl') ?? false,
          username: this.stringValue(valuesArg.username),
          password: this.stringValue(valuesArg.password),
          name: this.stringValue(valuesArg.name) || candidateArg.name,
          uniqueId: candidateArg.id,
          timeoutMs: defaultTimeoutMs,
        },
      }),
    };
  }

  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 booleanValue(valueArg: unknown): boolean | undefined {
    return typeof valueArg === 'boolean' ? valueArg : undefined;
  }

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

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