import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IAirgradientConfig, IAirgradientDeviceConfig, IAirgradientMeasures, TAirgradientProtocol } from './airgradient.types.js';
import { airgradientDefaultPort, airgradientMinFirmwareVersion } from './airgradient.types.js';
import { versionAtLeast } from './airgradient.discovery.js';

export class AirgradientConfigFlow implements IConfigFlow<IAirgradientConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IAirgradientConfig>> {
    void contextArg;
    const defaults = this.defaultsFromCandidate(candidateArg);
    return {
      kind: 'form',
      title: 'Connect AirGradient',
      description: 'Configure the local AirGradient HTTP endpoint. Supported firmware starts at 3.1.1.',
      fields: [
        { name: 'host', label: 'Host or IP address', type: 'text', required: true },
        { name: 'port', label: 'HTTP port', type: 'number' },
        { name: 'protocol', label: 'Protocol', type: 'select', options: [{ label: 'HTTP', value: 'http' }, { label: 'HTTPS', value: 'https' }] },
        { name: 'name', label: 'Device name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || defaults.host;
        if (!host) {
          return { kind: 'error', title: 'Invalid AirGradient config', error: 'AirGradient setup requires a host or IP address.' };
        }
        if (defaults.firmwareVersion && !versionAtLeast(defaults.firmwareVersion, airgradientMinFirmwareVersion)) {
          return { kind: 'error', title: 'Unsupported AirGradient firmware', error: `AirGradient firmware ${defaults.firmwareVersion} is below the supported minimum ${airgradientMinFirmwareVersion}.` };
        }
        const protocol = this.protocolValue(valuesArg.protocol) || defaults.protocol || 'http';
        const port = this.numberValue(valuesArg.port) || defaults.port || airgradientDefaultPort;
        const name = this.stringValue(valuesArg.name) || defaults.name;
        return {
          kind: 'done',
          title: 'AirGradient configured',
          config: {
            host,
            port,
            protocol,
            name,
            uniqueId: defaults.id,
            serialNumber: defaults.serialNumber,
            model: defaults.model,
            firmwareVersion: defaults.firmwareVersion,
            measures: defaults.measures,
            deviceConfig: defaults.deviceConfig,
            deviceInfo: {
              host,
              port,
              protocol,
              name,
              serialNumber: defaults.serialNumber,
              model: defaults.model,
              firmwareVersion: defaults.firmwareVersion,
            },
          },
        };
      },
    };
  }

  private defaultsFromCandidate(candidateArg: IDiscoveryCandidate): {
    id?: string;
    host?: string;
    port?: number;
    protocol?: TAirgradientProtocol;
    name?: string;
    serialNumber?: string;
    model?: string;
    firmwareVersion?: string;
    measures?: IAirgradientMeasures;
    deviceConfig?: IAirgradientDeviceConfig;
  } {
    const metadata = candidateArg.metadata || {};
    return {
      id: candidateArg.id,
      host: candidateArg.host,
      port: candidateArg.port || airgradientDefaultPort,
      protocol: this.protocolValue(metadata.protocol),
      name: candidateArg.name,
      serialNumber: candidateArg.serialNumber || candidateArg.id,
      model: candidateArg.model,
      firmwareVersion: this.stringValue(metadata.firmwareVersion),
      measures: this.recordValue(metadata.measures) as IAirgradientMeasures | undefined,
      deviceConfig: this.recordValue(metadata.deviceConfig) as IAirgradientDeviceConfig | undefined,
    };
  }

  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() && Number.isFinite(Number(valueArg))) {
      return Number(valueArg);
    }
    return undefined;
  }

  private protocolValue(valueArg: unknown): TAirgradientProtocol | undefined {
    return valueArg === 'http' || valueArg === 'https' ? valueArg : undefined;
  }

  private recordValue(valueArg: unknown): Record<string, unknown> | undefined {
    return typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg) ? valueArg as Record<string, unknown> : undefined;
  }
}
