import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IHddtempConfig, IHddtempSnapshot, THddtempRawData } from './hddtemp.types.js';
import { hddtempDefaultName, hddtempDefaultPort, hddtempDefaultTimeoutMs } from './hddtemp.types.js';

export class HddtempConfigFlow implements IConfigFlow<IHddtempConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IHddtempConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect hddtemp',
      description: 'Configure a local hddtemp daemon TCP endpoint or provide raw daemon output for read-only snapshots.',
      fields: [
        { name: 'host', label: 'Host', type: 'text' },
        { name: 'port', label: 'TCP port', type: 'number' },
        { name: 'disks', label: 'Disks to expose (comma separated)', type: 'text' },
        { name: 'name', label: 'Sensor name prefix', type: 'text' },
        { name: 'rawData', label: 'Raw hddtemp daemon output', type: 'text' },
      ],
      submit: async (valuesArg) => this.submit(candidateArg, valuesArg),
    };
  }

  private async submit(candidateArg: IDiscoveryCandidate, valuesArg: Record<string, unknown>): Promise<IConfigFlowStep<IHddtempConfig>> {
    const metadata = candidateArg.metadata || {};
    const endpoint = parseEndpoint(this.stringValue(valuesArg.host) || this.stringMetadata(metadata, 'url'));
    const snapshot = snapshotValue(valuesArg.snapshot || metadata.snapshot);
    const rawData = rawDataValue(valuesArg.rawData) ?? rawDataValue(metadata.rawData) ?? rawDataValue(metadata.rawText) ?? rawDataValue(metadata.banner);
    const host = endpoint?.host || this.stringValue(valuesArg.host) || candidateArg.host || snapshot?.daemon.host;
    const port = this.numberValue(valuesArg.port) || endpoint?.port || candidateArg.port || snapshot?.daemon.port || hddtempDefaultPort;
    const disks = this.disksValue(valuesArg.disks) || this.disksValue(metadata.disks) || snapshot?.daemon.configuredDisks || snapshot?.disks.map((diskArg) => diskArg.device);
    const client = metadata.client as IHddtempConfig['client'];
    const hasOfflineData = Boolean(snapshot || rawData || client);

    if (!host && !hasOfflineData) {
      return { kind: 'error', title: 'hddtemp setup failed', error: 'hddtemp host, injected client, snapshot, or raw data is required.' };
    }
    if (!this.validPort(port)) {
      return { kind: 'error', title: 'hddtemp setup failed', error: 'hddtemp port must be between 1 and 65535.' };
    }

    return {
      kind: 'done',
      title: 'hddtemp configured',
      config: {
        host,
        port,
        disks,
        name: this.stringValue(valuesArg.name) || candidateArg.name || snapshot?.daemon.name || this.stringMetadata(metadata, 'name') || hddtempDefaultName,
        uniqueId: candidateArg.id || snapshot?.daemon.id || (host ? `${host}:${port}` : undefined),
        transport: host ? 'tcp' : 'snapshot',
        timeoutMs: hddtempDefaultTimeoutMs,
        snapshot,
        rawData,
        client,
      },
    };
  }

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;
  }

  private stringMetadata(metadataArg: Record<string, unknown>, keyArg: string): string | undefined {
    return this.stringValue(metadataArg[keyArg]);
  }

  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 validPort(valueArg: number): boolean {
    return Number.isInteger(valueArg) && valueArg > 0 && valueArg <= 65535;
  }

  private disksValue(valueArg: unknown): string[] | undefined {
    if (Array.isArray(valueArg)) {
      const disks = valueArg.filter((diskArg): diskArg is string => typeof diskArg === 'string' && Boolean(diskArg.trim())).map((diskArg) => diskArg.trim());
      return disks.length ? disks : undefined;
    }
    if (typeof valueArg === 'string' && valueArg.trim()) {
      const disks = valueArg.split(/[,;\s]+/).map((diskArg) => diskArg.trim()).filter(Boolean);
      return disks.length ? disks : undefined;
    }
    return undefined;
  }
}

const parseEndpoint = (valueArg: string | undefined): { host: string; port?: number } | undefined => {
  if (!valueArg || !/^[a-z][a-z0-9+.-]*:\/\//i.test(valueArg)) {
    return undefined;
  }
  try {
    const url = new URL(valueArg);
    return { host: url.hostname, port: url.port ? Number(url.port) : undefined };
  } catch {
    return undefined;
  }
};

const snapshotValue = (valueArg: unknown): IHddtempSnapshot | undefined => {
  return valueArg && typeof valueArg === 'object' && 'daemon' in valueArg && 'disks' in valueArg ? valueArg as IHddtempSnapshot : undefined;
};

const rawDataValue = (valueArg: unknown): THddtempRawData | undefined => {
  if (typeof valueArg === 'string' && valueArg.trim()) {
    return valueArg;
  }
  if (Array.isArray(valueArg)) {
    return valueArg as THddtempRawData;
  }
  return undefined;
};
