import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IOpenRGBConfig, IOpenRGBController, IOpenRGBSnapshot } from './openrgb.types.js';
import { openrgbDefaultClientName, openrgbDefaultPort } from './openrgb.types.js';

export class OpenRGBConfigFlow implements IConfigFlow<IOpenRGBConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IOpenRGBConfig>> {
    void contextArg;
    const defaults = this.defaultsFromCandidate(candidateArg);
    return {
      kind: 'form',
      title: 'Connect OpenRGB',
      description: 'Configure the local OpenRGB SDK server. OpenRGB uses TCP port 6742 by default.',
      fields: [
        { name: 'name', label: 'Name', type: 'text', required: true },
        { name: 'host', label: 'Host or IP address', type: 'text', required: true },
        { name: 'port', label: 'SDK port', type: 'number' },
        { name: 'clientName', label: 'SDK client name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || defaults.host;
        if (!host) {
          return { kind: 'error', title: 'Invalid OpenRGB config', error: 'OpenRGB setup requires a host or IP address.' };
        }
        const port = this.numberValue(valuesArg.port) || defaults.port || openrgbDefaultPort;
        if (!Number.isInteger(port) || port <= 0 || port > 65535) {
          return { kind: 'error', title: 'Invalid OpenRGB config', error: 'OpenRGB SDK port must be an integer between 1 and 65535.' };
        }
        const name = this.stringValue(valuesArg.name) || defaults.name || 'OpenRGB SDK Server';
        const clientName = this.stringValue(valuesArg.clientName) || defaults.clientName || openrgbDefaultClientName;
        return {
          kind: 'done',
          title: 'OpenRGB configured',
          config: {
            entryId: defaults.entryId,
            name,
            host,
            port,
            clientName,
            protocolVersion: defaults.protocolVersion,
            controller: {
              ...defaults.controller,
              name,
              host,
              port,
            },
            snapshot: defaults.snapshot,
            devices: defaults.devices,
            profiles: defaults.profiles,
          },
        };
      },
    };
  }

  private defaultsFromCandidate(candidateArg: IDiscoveryCandidate): {
    entryId?: string;
    host?: string;
    port?: number;
    name?: string;
    clientName?: string;
    protocolVersion?: number;
    controller?: IOpenRGBController;
    snapshot?: IOpenRGBSnapshot;
    devices?: IOpenRGBConfig['devices'];
    profiles?: string[];
  } {
    const metadata = candidateArg.metadata || {};
    const snapshot = this.isRecord(metadata.snapshot) ? metadata.snapshot as unknown as IOpenRGBSnapshot : undefined;
    const controller = this.isRecord(metadata.controller) ? metadata.controller as unknown as IOpenRGBController : undefined;
    const devices = Array.isArray(metadata.devices) ? metadata.devices as IOpenRGBConfig['devices'] : undefined;
    const profiles = Array.isArray(metadata.profiles) ? metadata.profiles.filter((profileArg): profileArg is string => typeof profileArg === 'string') : undefined;
    return {
      entryId: candidateArg.id,
      host: candidateArg.host || snapshot?.host,
      port: candidateArg.port || snapshot?.port || openrgbDefaultPort,
      name: candidateArg.name || snapshot?.name || controller?.name,
      clientName: this.stringValue(metadata.clientName) || openrgbDefaultClientName,
      protocolVersion: this.numberValue(metadata.protocolVersion) || snapshot?.protocolVersion,
      controller,
      snapshot,
      devices,
      profiles,
    };
  }

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