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

export class YamahaMusiccastConfigFlow implements IConfigFlow<IYamahaMusiccastConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IYamahaMusiccastConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Yamaha MusicCast Device',
      description: 'Configure the local Yamaha MusicCast HTTP endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: '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: 'Yamaha MusicCast setup failed',
            error: 'Host is required.',
          };
        }
        const port = numberValue(valuesArg.port) ?? candidateArg.port ?? 80;
        const name = stringValue(valuesArg.name) || candidateArg.name;
        const model = stringValue(valuesArg.model) || candidateArg.model;
        const systemId = stringMetadata(candidateArg.metadata?.systemId);
        const deviceId = stringMetadata(candidateArg.metadata?.deviceId);
        return {
          kind: 'done',
          title: 'Yamaha MusicCast configured',
          config: {
            host,
            port,
            name,
            model,
            manufacturer: candidateArg.manufacturer,
            serialNumber: candidateArg.serialNumber,
            systemId,
            deviceId,
            deviceInfo: name || model || candidateArg.serialNumber || systemId || deviceId ? {
              model_name: model,
              serial_number: candidateArg.serialNumber,
              system_id: systemId,
              device_id: deviceId,
            } : undefined,
          },
        };
      },
    };
  }
}

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

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