import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IArcamFmjConfig } from './arcam_fmj.types.js';
import { arcamFmjDefaultPort } from './arcam_fmj.types.js';

export class ArcamFmjConfigFlow implements IConfigFlow<IArcamFmjConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IArcamFmjConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Arcam FMJ Receiver',
      description: 'Configure the local Arcam FMJ TCP control endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'TCP port', type: 'number' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'model', label: 'Model', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = stringValue(valuesArg.host) || candidateArg.host;
        if (!host) {
          return { kind: 'error', title: 'Arcam FMJ setup failed', error: 'Arcam FMJ host is required.' };
        }
        const port = numberValue(valuesArg.port) || candidateArg.port || arcamFmjDefaultPort;
        const name = stringValue(valuesArg.name) || candidateArg.name;
        const model = stringValue(valuesArg.model) || candidateArg.model;
        return {
          kind: 'done',
          title: 'Arcam FMJ configured',
          config: {
            host,
            port,
            name,
            model,
            manufacturer: candidateArg.manufacturer || 'Arcam',
            serialNumber: candidateArg.serialNumber,
            uniqueId: candidateArg.id || candidateArg.serialNumber || `${host}:${port}`,
          },
        };
      },
    };
  }
}

const stringValue = (valueArg: unknown): string | undefined => {
  return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;
};

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