import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IGlancesConfig, IGlancesHaSensorData, IGlancesRawData, IGlancesSnapshot, TGlancesApiVersion } from './glances.types.js';
import { glancesDefaultPort, glancesDefaultTimeoutMs } from './glances.types.js';

export class GlancesConfigFlow implements IConfigFlow<IGlancesConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IGlancesConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Glances',
      description: 'Configure a local Glances REST API endpoint, or use snapshot/manual data from the discovery candidate.',
      fields: [
        { name: 'host', label: 'Host', type: 'text' },
        { name: 'port', label: 'HTTP port', type: 'number' },
        { name: 'ssl', label: 'Use HTTPS', type: 'boolean' },
        { name: 'verifySsl', label: 'Verify TLS certificate', type: 'boolean' },
        { name: 'username', label: 'Username', type: 'text' },
        { name: 'password', label: 'Password', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'apiVersion', label: 'API version', type: 'select', options: [
          { label: 'Auto (v4 then v3)', value: 'auto' },
          { label: 'v4', value: '4' },
          { label: 'v3', value: '3' },
        ] },
      ],
      submit: async (valuesArg) => this.submit(candidateArg, valuesArg),
    };
  }

  private async submit(candidateArg: IDiscoveryCandidate, valuesArg: Record<string, unknown>): Promise<IConfigFlowStep<IGlancesConfig>> {
    const metadata = candidateArg.metadata || {};
    const host = this.stringValue(valuesArg.host) || candidateArg.host;
    const port = this.numberValue(valuesArg.port) || candidateArg.port || glancesDefaultPort;
    const ssl = this.booleanValue(valuesArg.ssl) ?? this.booleanValue(metadata.ssl) ?? false;
    const verifySsl = this.booleanValue(valuesArg.verifySsl) ?? this.booleanValue(metadata.verifySsl) ?? false;
    const username = this.stringValue(valuesArg.username) || this.stringValue(metadata.username);
    const password = this.stringValue(valuesArg.password) || this.stringValue(metadata.password);
    const apiVersion = this.apiVersionValue(valuesArg.apiVersion) || this.apiVersionValue(metadata.apiVersion);
    const snapshot = this.snapshotValue(metadata.snapshot);
    const rawData = this.rawDataValue(metadata.rawData || metadata.allData);
    const haSensorData = this.sensorDataValue(metadata.haSensorData || metadata.sensorData);

    if (!host && !snapshot && !rawData && !haSensorData) {
      return { kind: 'error', title: 'Glances setup failed', error: 'Glances host or snapshot/manual sensor data is required.' };
    }
    if (!this.validPort(port)) {
      return { kind: 'error', title: 'Glances setup failed', error: 'Glances port must be between 1 and 65535.' };
    }
    if (password && !username) {
      return { kind: 'error', title: 'Glances setup failed', error: 'Glances username is required when password is provided.' };
    }

    const config: IGlancesConfig = {
      host,
      port,
      ssl,
      verifySsl,
      username,
      password,
      apiVersion,
      name: this.stringValue(valuesArg.name) || candidateArg.name || this.stringValue(metadata.name),
      uniqueId: candidateArg.id || (host ? `${host}:${port}` : undefined),
      timeoutMs: glancesDefaultTimeoutMs,
      snapshot,
      rawData,
      haSensorData,
    };

    return {
      kind: 'done',
      title: 'Glances configured',
      config,
    };
  }

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

  private booleanValue(valueArg: unknown): boolean | undefined {
    if (typeof valueArg === 'boolean') {
      return valueArg;
    }
    if (typeof valueArg === 'string') {
      if (valueArg.toLowerCase() === 'true') {
        return true;
      }
      if (valueArg.toLowerCase() === 'false') {
        return false;
      }
    }
    return undefined;
  }

  private apiVersionValue(valueArg: unknown): TGlancesApiVersion | undefined {
    const value = typeof valueArg === 'number' ? String(valueArg) : this.stringValue(valueArg);
    if (value === '3' || value === '4') {
      return Number(value) as TGlancesApiVersion;
    }
    return undefined;
  }

  private validPort(valueArg: number): boolean {
    return Number.isInteger(valueArg) && valueArg > 0 && valueArg <= 65535;
  }

  private snapshotValue(valueArg: unknown): IGlancesSnapshot | undefined {
    return this.isRecord(valueArg) && 'host' in valueArg && 'sensorData' in valueArg ? valueArg as unknown as IGlancesSnapshot : undefined;
  }

  private rawDataValue(valueArg: unknown): IGlancesRawData | undefined {
    return this.isRecord(valueArg) ? valueArg as IGlancesRawData : undefined;
  }

  private sensorDataValue(valueArg: unknown): IGlancesHaSensorData | undefined {
    return this.isRecord(valueArg) ? valueArg as IGlancesHaSensorData : undefined;
  }

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