import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import { SynologyDsmMapper } from './synology_dsm.mapper.js';
import type { ISynologyDsmConfig, ISynologyDsmSnapshot } from './synology_dsm.types.js';
import { synologyDsmDefaultSnapshotQuality, synologyDsmDefaultSsl, synologyDsmDefaultTimeoutMs, synologyDsmDefaultVerifySsl } from './synology_dsm.types.js';

export class SynologyDsmConfigFlow implements IConfigFlow<ISynologyDsmConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<ISynologyDsmConfig>> {
    void contextArg;
    const metadata = candidateArg.metadata || {};
    const ssl = this.booleanValue(metadata.ssl) ?? synologyDsmDefaultSsl;
    return {
      kind: 'form',
      title: 'Connect Synology DSM',
      description: 'Provide the local DSM endpoint. Snapshot/manual data and injected native clients are supported directly; live DSM API success is not assumed without a native client or snapshot provider.',
      fields: [
        { name: 'host', label: candidateArg.host ? `Host (${candidateArg.host})` : 'Host', type: 'text', required: true },
        { name: 'port', label: `Port (${candidateArg.port || SynologyDsmMapper.defaultPort(ssl)})`, 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: 'serial', label: 'Serial', type: 'text' },
        { name: 'snapshotQuality', label: 'Surveillance Station snapshot quality', type: 'select', options: [
          { label: 'Low', value: '0' },
          { label: 'Balanced', value: '1' },
          { label: 'High', value: '2' },
        ] },
        { name: 'snapshotJson', label: 'Snapshot JSON', type: 'text' },
      ],
      submit: async (valuesArg) => this.submit(candidateArg, valuesArg),
    };
  }

  private async submit(candidateArg: IDiscoveryCandidate, valuesArg: Record<string, unknown>): Promise<IConfigFlowStep<ISynologyDsmConfig>> {
    const metadata = candidateArg.metadata || {};
    const snapshot = this.snapshotFromInput(valuesArg.snapshotJson || metadata.snapshot);
    if (snapshot instanceof Error) {
      return { kind: 'error', title: 'Invalid Synology DSM snapshot', error: snapshot.message };
    }

    const ssl = this.booleanValue(valuesArg.ssl) ?? this.booleanValue(metadata.ssl) ?? snapshot?.system.ssl ?? synologyDsmDefaultSsl;
    const host = this.stringValue(valuesArg.host) || candidateArg.host || snapshot?.system.host;
    if (!host && !snapshot) {
      return { kind: 'error', title: 'Synology DSM setup failed', error: 'Synology DSM setup requires a host or snapshot JSON.' };
    }

    const port = this.numberValue(valuesArg.port) || candidateArg.port || snapshot?.system.port || SynologyDsmMapper.defaultPort(ssl);
    if (!this.validPort(port)) {
      return { kind: 'error', title: 'Synology DSM setup failed', error: 'Synology DSM port must be between 1 and 65535.' };
    }
    const username = this.stringValue(valuesArg.username) || this.stringValue(metadata.username);
    const password = this.stringValue(valuesArg.password) || this.stringValue(metadata.password);
    if (password && !username) {
      return { kind: 'error', title: 'Synology DSM setup failed', error: 'Username is required when a password is provided.' };
    }

    const config: ISynologyDsmConfig = {
      host,
      port,
      ssl,
      verifySsl: this.booleanValue(valuesArg.verifySsl) ?? this.booleanValue(metadata.verifySsl) ?? snapshot?.system.verifySsl ?? synologyDsmDefaultVerifySsl,
      username,
      password,
      timeoutMs: synologyDsmDefaultTimeoutMs,
      name: this.stringValue(valuesArg.name) || candidateArg.name || snapshot?.system.name || snapshot?.system.hostname || host,
      serial: this.stringValue(valuesArg.serial) || candidateArg.serialNumber || snapshot?.system.serial,
      uniqueId: candidateArg.id || snapshot?.system.serial || candidateArg.serialNumber || candidateArg.macAddress || (host ? `${host}:${port}` : undefined),
      macAddress: candidateArg.macAddress,
      macs: snapshot?.system.macs,
      snapshotQuality: this.numberValue(valuesArg.snapshotQuality) ?? synologyDsmDefaultSnapshotQuality,
      snapshot,
      metadata: {
        discoverySource: candidateArg.source,
        discoveryMetadata: metadata,
        upstreamSupportsSsdp: true,
        upstreamSupportsZeroconf: true,
        liveHttpImplemented: false,
      },
    };

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

  private snapshotFromInput(valueArg: unknown): ISynologyDsmSnapshot | undefined | Error {
    if (valueArg && typeof valueArg === 'object') {
      return valueArg as ISynologyDsmSnapshot;
    }
    const text = this.stringValue(valueArg);
    if (!text) {
      return undefined;
    }
    try {
      const parsed = JSON.parse(text) as ISynologyDsmSnapshot;
      if (!parsed || typeof parsed !== 'object' || !parsed.system) {
        return new Error('Snapshot JSON must include a system object.');
      }
      return parsed;
    } catch (errorArg) {
      return errorArg instanceof Error ? errorArg : new Error(String(errorArg));
    }
  }

  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 (['true', '1', 'yes', 'on'].includes(valueArg.toLowerCase())) {
        return true;
      }
      if (['false', '0', 'no', 'off'].includes(valueArg.toLowerCase())) {
        return false;
      }
    }
    return undefined;
  }

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