import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IDunehdConfig } from './dunehd.types.js';
import { dunehdDefaultName, dunehdDefaultPort } from './dunehd.types.js';

export class DunehdConfigFlow implements IConfigFlow<IDunehdConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IDunehdConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Dune HD',
      description: 'Configure the local Dune HD HTTP CGI endpoint. Ensure the player is powered on before validating live control.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'HTTP port', type: 'number' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'model', label: 'Model', type: 'text' },
      ],
      submit: async (valuesArg) => this.submit(candidateArg, valuesArg),
    };
  }

  private async submit(candidateArg: IDiscoveryCandidate, valuesArg: Record<string, unknown>): Promise<IConfigFlowStep<IDunehdConfig>> {
    const host = this.stringValue(valuesArg.host) || candidateArg.host;
    if (!host) {
      return { kind: 'error', error: 'Dune HD host is required.' };
    }
    if (!this.isHostValid(host)) {
      return { kind: 'error', error: 'Dune HD host is invalid.' };
    }

    const port = this.numberValue(valuesArg.port) || candidateArg.port || dunehdDefaultPort;
    const name = this.stringValue(valuesArg.name) || candidateArg.name || dunehdDefaultName;
    const model = this.stringValue(valuesArg.model) || candidateArg.model;
    return {
      kind: 'done',
      title: 'Dune HD configured',
      config: {
        host,
        port,
        name,
        model,
        manufacturer: candidateArg.manufacturer || 'Dune',
        uniqueId: candidateArg.id || candidateArg.serialNumber || candidateArg.macAddress || host,
        serialNumber: candidateArg.serialNumber,
        macAddress: candidateArg.macAddress,
        deviceInfo: {
          id: candidateArg.id || candidateArg.serialNumber || candidateArg.macAddress || host,
          host,
          port,
          name,
          manufacturer: candidateArg.manufacturer || 'Dune',
          model,
          serialNumber: candidateArg.serialNumber,
          macAddress: candidateArg.macAddress,
        },
        timeoutMs: 5000,
      },
    };
  }

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

  private isHostValid(hostArg: string): boolean {
    return hostArg.length <= 253 && !/[\s/]/.test(hostArg) && !hostArg.includes('://');
  }
}
