import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import { prusaLinkApiVersionSupported } from './prusalink.mapper.js';
import type { IPrusaLinkConfig, IPrusaLinkRawData, IPrusaLinkSnapshot, IPrusaLinkVersionInfo } from './prusalink.types.js';
import { prusaLinkDefaultPort, prusaLinkDefaultTimeoutMs, prusaLinkDefaultUsername } from './prusalink.types.js';

export class PrusaLinkConfigFlow implements IConfigFlow<IPrusaLinkConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IPrusaLinkConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect PrusaLink',
      description: 'Configure a local PrusaLink HTTP 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/API key', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => this.submit(candidateArg, valuesArg),
    };
  }

  private async submit(candidateArg: IDiscoveryCandidate, valuesArg: Record<string, unknown>): Promise<IConfigFlowStep<IPrusaLinkConfig>> {
    const metadata = candidateArg.metadata || {};
    const parsed = parseEndpoint(this.stringValue(valuesArg.host) || this.stringValue(metadata.url));
    const snapshot = snapshotValue(metadata.snapshot);
    const rawData = rawDataValue(metadata.rawData);
    const version = versionValue(metadata.version || rawData?.version);
    const host = parsed?.host || this.stringValue(valuesArg.host) || candidateArg.host || snapshot?.printer.host;
    const port = this.numberValue(valuesArg.port) || candidateArg.port || parsed?.port || snapshot?.printer.port || prusaLinkDefaultPort;
    const ssl = this.booleanValue(valuesArg.ssl) ?? parsed?.ssl ?? this.booleanMetadata(metadata, 'ssl') ?? this.booleanMetadata(metadata, 'tls') ?? snapshot?.printer.ssl ?? false;
    const hasManualData = Boolean(snapshot || rawData || metadata.client);

    if (!host && !hasManualData) {
      return { kind: 'error', title: 'PrusaLink setup failed', error: 'PrusaLink host, injected client, or snapshot/manual data is required.' };
    }
    if (!this.validPort(port)) {
      return { kind: 'error', title: 'PrusaLink setup failed', error: 'PrusaLink port must be between 1 and 65535.' };
    }
    if (host && !hasManualData && !this.stringValue(valuesArg.password) && !this.stringMetadata(metadata, 'password') && !this.stringMetadata(metadata, 'apiKey')) {
      return { kind: 'error', title: 'PrusaLink setup failed', error: 'PrusaLink password/API key is required for live HTTP setup.' };
    }
    if (!prusaLinkApiVersionSupported(version || snapshot?.rawData?.version)) {
      return { kind: 'error', title: 'PrusaLink setup failed', error: 'Only PrusaLink API v2 is supported.' };
    }

    const config: IPrusaLinkConfig = {
      host,
      port,
      ssl,
      verifySsl: this.booleanValue(valuesArg.verifySsl) ?? this.booleanMetadata(metadata, 'verifySsl') ?? false,
      username: this.stringValue(valuesArg.username) || this.stringMetadata(metadata, 'username') || prusaLinkDefaultUsername,
      password: this.stringValue(valuesArg.password) || this.stringMetadata(metadata, 'password') || this.stringMetadata(metadata, 'apiKey'),
      name: this.stringValue(valuesArg.name) || candidateArg.name || snapshot?.printer.name || this.stringMetadata(metadata, 'name'),
      manufacturer: candidateArg.manufacturer || snapshot?.printer.manufacturer || 'Prusa',
      model: candidateArg.model || snapshot?.printer.model,
      uniqueId: candidateArg.id || snapshot?.printer.id || snapshot?.printer.serialNumber || (host ? `${host}:${port}` : undefined),
      timeoutMs: prusaLinkDefaultTimeoutMs,
      snapshot,
      rawData,
      client: metadata.client as IPrusaLinkConfig['client'],
      commandExecutor: metadata.commandExecutor as IPrusaLinkConfig['commandExecutor'],
    };

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

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim().replace(/\/$/, '') : 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') {
      const normalized = valueArg.trim().toLowerCase();
      if (['true', 'yes', 'on', '1'].includes(normalized)) {
        return true;
      }
      if (['false', 'no', 'off', '0'].includes(normalized)) {
        return false;
      }
    }
    return undefined;
  }

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

  private booleanMetadata(metadataArg: Record<string, unknown>, keyArg: string): boolean | undefined {
    const value = metadataArg[keyArg];
    return typeof value === 'boolean' ? value : undefined;
  }

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

const parseEndpoint = (valueArg: string | undefined): { host: string; port?: number; ssl: boolean } | 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,
      ssl: url.protocol === 'https:',
    };
  } catch {
    return undefined;
  }
};

const snapshotValue = (valueArg: unknown): IPrusaLinkSnapshot | undefined => {
  return valueArg && typeof valueArg === 'object' && 'printer' in valueArg && 'telemetry' in valueArg ? valueArg as IPrusaLinkSnapshot : undefined;
};

const rawDataValue = (valueArg: unknown): Partial<IPrusaLinkRawData> | undefined => {
  return valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg) ? valueArg as Partial<IPrusaLinkRawData> : undefined;
};

const versionValue = (valueArg: unknown): IPrusaLinkVersionInfo | undefined => {
  return valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg) ? valueArg as IPrusaLinkVersionInfo : undefined;
};
