import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IDenonConfig, IDenonSnapshot } from './denon.types.js';
import { denonDefaultName, denonDefaultPort } from './denon.types.js';

export class DenonConfigFlow implements IConfigFlow<IDenonConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IDenonConfig>> {
    void contextArg;
    const metadata = candidateArg.metadata || {};
    const snapshot = metadata.snapshot as IDenonSnapshot | undefined;
    const hasInjectedRuntime = Boolean(snapshot || metadata.client || metadata.commandExecutor);
    return {
      kind: 'form',
      title: 'Connect Denon Network Receiver',
      description: hasInjectedRuntime
        ? 'Configure the Denon receiver using the discovered snapshot or injected runtime.'
        : 'Configure the local Denon receiver telnet endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: !hasInjectedRuntime },
        { name: 'port', label: 'Telnet port', type: 'number' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'model', label: 'Model', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const port = numberValue(valuesArg.port) || candidateArg.port || snapshot?.receiverInfo.port || denonDefaultPort;
        return {
          kind: 'done',
          title: 'Denon receiver configured',
          config: {
            host: stringValue(valuesArg.host) || candidateArg.host || snapshot?.receiverInfo.host,
            port,
            name: stringValue(valuesArg.name) || candidateArg.name || snapshot?.receiverInfo.name || denonDefaultName,
            manufacturer: candidateArg.manufacturer || snapshot?.receiverInfo.manufacturer || 'Denon',
            model: stringValue(valuesArg.model) || candidateArg.model || snapshot?.receiverInfo.modelName,
            serialNumber: candidateArg.serialNumber || snapshot?.receiverInfo.serialNumber,
            sourceMap: metadata.sourceMap as IDenonConfig['sourceMap'],
            snapshot,
            client: metadata.client as IDenonConfig['client'],
            commandExecutor: metadata.commandExecutor as IDenonConfig['commandExecutor'],
          },
        };
      },
    };
  }
}

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

const numberValue = (valueArg: unknown): number | undefined => {
  const value = typeof valueArg === 'number' ? valueArg : typeof valueArg === 'string' && valueArg.trim() ? Number(valueArg) : undefined;
  return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
};
