import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IWizConfig, IWizDeviceInfo, IWizPilotState, IWizSnapshot } from './wiz.types.js';
import { wizDefaultPort } from './wiz.types.js';

export class WizConfigFlow implements IConfigFlow<IWizConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IWizConfig>> {
    void contextArg;
    const defaults = this.defaultsFromCandidate(candidateArg);
    return {
      kind: 'form',
      title: 'Connect WiZ',
      description: 'Configure the WiZ device host. Local control uses UDP JSON on port 38899 by default.',
      fields: [
        { name: 'host', label: 'Host or IP address', type: 'text', required: true },
        { name: 'port', label: 'UDP port (default 38899)', type: 'number' },
        { name: 'mac', label: 'MAC address', type: 'text' },
        { 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 WiZ config', error: 'WiZ setup requires a host or IP address.' };
        }
        const port = this.numberValue(valuesArg.port) || defaults.port || wizDefaultPort;
        const mac = this.stringValue(valuesArg.mac) || defaults.mac;
        const name = this.stringValue(valuesArg.name) || defaults.name;
        return {
          kind: 'done',
          title: 'WiZ configured',
          config: {
            host,
            port,
            mac,
            name,
            deviceInfo: {
              ...defaults.deviceInfo,
              host,
              port,
              mac: mac || defaults.deviceInfo?.mac,
              name: name || defaults.deviceInfo?.name,
            },
            pilot: defaults.pilot,
            snapshot: defaults.snapshot,
          },
        };
      },
    };
  }

  private defaultsFromCandidate(candidateArg: IDiscoveryCandidate): { host?: string; port?: number; mac?: string; name?: string; deviceInfo?: IWizDeviceInfo; pilot?: IWizPilotState; snapshot?: IWizSnapshot } {
    const metadata = candidateArg.metadata || {};
    const deviceInfo = this.isRecord(metadata.deviceInfo) ? metadata.deviceInfo as unknown as IWizDeviceInfo : undefined;
    const pilot = this.isRecord(metadata.pilot) ? metadata.pilot as unknown as IWizPilotState : undefined;
    const snapshot = this.isRecord(metadata.snapshot) ? metadata.snapshot as unknown as IWizSnapshot : undefined;
    return {
      host: candidateArg.host,
      port: candidateArg.port || wizDefaultPort,
      mac: candidateArg.macAddress,
      name: candidateArg.name,
      deviceInfo,
      pilot,
      snapshot,
    };
  }

  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 parsed = Number(valueArg);
      return Number.isFinite(parsed) ? parsed : undefined;
    }
    return undefined;
  }

  private isRecord(valueArg: unknown): valueArg is Record<string, unknown> {
    return typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg);
  }
}
