import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import { SynologySrmMapper } from './synology_srm.mapper.js';
import type { ISynologySrmConfig, ISynologySrmSnapshot } from './synology_srm.types.js';
import { synologySrmDefaultConsiderHomeSeconds, synologySrmDefaultSsl, synologySrmDefaultUsername, synologySrmDefaultVerifySsl } from './synology_srm.types.js';

export class SynologySrmConfigFlow implements IConfigFlow<ISynologySrmConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<ISynologySrmConfig>> {
    void contextArg;
    const metadata = candidateArg.metadata || {};
    const ssl = this.booleanValue(metadata.ssl) ?? synologySrmDefaultSsl;
    return {
      kind: 'form',
      title: 'Connect Synology SRM',
      description: 'Provide the local SRM router endpoint. Snapshot/manual data and injected native clients are supported directly; live SRM 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 || SynologySrmMapper.defaultPort(ssl)})`, type: 'number' },
        { name: 'ssl', label: 'Use HTTPS', type: 'boolean' },
        { name: 'verifySsl', label: 'Verify TLS certificate', type: 'boolean' },
        { name: 'username', label: `Username (${synologySrmDefaultUsername})`, type: 'text' },
        { name: 'password', label: 'Password', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
        { 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<ISynologySrmConfig>> {
    const metadata = candidateArg.metadata || {};
    const snapshot = this.snapshotFromInput(valuesArg.snapshotJson || metadata.snapshot);
    if (snapshot instanceof Error) {
      return { kind: 'error', title: 'Invalid Synology SRM snapshot', error: snapshot.message };
    }

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

    const port = this.numberValue(valuesArg.port) || candidateArg.port || snapshot?.router.port || SynologySrmMapper.defaultPort(ssl);
    if (!this.validPort(port)) {
      return { kind: 'error', title: 'Synology SRM setup failed', error: 'Synology SRM port must be between 1 and 65535.' };
    }

    const username = this.stringValue(valuesArg.username) || this.stringValue(metadata.username) || synologySrmDefaultUsername;
    const password = this.stringValue(valuesArg.password) || this.stringValue(metadata.password);
    const mac = SynologySrmMapper.normalizeMac(candidateArg.macAddress || snapshot?.router.macAddress || snapshot?.network?.macs?.[0]);
    const config: ISynologySrmConfig = {
      host,
      port,
      ssl,
      verifySsl: this.booleanValue(valuesArg.verifySsl) ?? this.booleanValue(metadata.verifySsl) ?? snapshot?.router.verifySsl ?? synologySrmDefaultVerifySsl,
      username,
      password,
      considerHomeSeconds: synologySrmDefaultConsiderHomeSeconds,
      uniqueId: candidateArg.id || snapshot?.router.id || snapshot?.router.serialNumber || mac || (host ? `${host}:${port}` : undefined),
      name: this.stringValue(valuesArg.name) || candidateArg.name || snapshot?.router.name || snapshot?.router.hostname || host,
      snapshot,
      metadata: {
        discoverySource: candidateArg.source,
        discoveryMetadata: metadata,
        upstreamDeviceTrackerOnly: true,
        liveSrmApiImplemented: false,
      },
    };

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

  private snapshotFromInput(valueArg: unknown): ISynologySrmSnapshot | undefined | Error {
    if (valueArg && typeof valueArg === 'object') {
      return valueArg as ISynologySrmSnapshot;
    }
    const text = this.stringValue(valueArg);
    if (!text) {
      return undefined;
    }
    try {
      const parsed = JSON.parse(text) as ISynologySrmSnapshot;
      if (!parsed || typeof parsed !== 'object' || !parsed.router) {
        return new Error('Snapshot JSON must include a router 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;
  }
}
