import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import { MikrotikMapper } from './mikrotik.mapper.js';
import type { IMikrotikConfig, IMikrotikSnapshot } from './mikrotik.types.js';
import { mikrotikDefaultApiPort, mikrotikDefaultDetectionTime } from './mikrotik.types.js';

export class MikrotikConfigFlow implements IConfigFlow<IMikrotikConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IMikrotikConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Set up Mikrotik Router',
      description: 'Provide the local RouterOS API endpoint. Snapshot/manual data is supported directly; live RouterOS/API success is not assumed without an injected native client or command executor.',
      fields: [
        { name: 'host', label: candidateArg.host ? `Host (${candidateArg.host})` : 'Host', type: 'text', required: true },
        { name: 'username', label: 'Username', type: 'text' },
        { name: 'password', label: 'Password', type: 'password' },
        { name: 'port', label: `API port (${candidateArg.port || mikrotikDefaultApiPort})`, type: 'number' },
        { name: 'verifySsl', label: 'Use SSL/TLS for RouterOS API', type: 'boolean' },
        { name: 'forceDhcp', label: 'Force scanning using DHCP', type: 'boolean' },
        { name: 'arpPing', label: 'Enable ARP ping', type: 'boolean' },
        { name: 'detectionTime', label: `Consider home interval (${mikrotikDefaultDetectionTime}s)`, type: 'number' },
        { 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<IMikrotikConfig>> {
    const snapshot = this.snapshotFromInput(valuesArg.snapshotJson || candidateArg.metadata?.snapshot);
    if (snapshot instanceof Error) {
      return { kind: 'error', title: 'Invalid Mikrotik snapshot', error: snapshot.message };
    }

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

    const port = this.numberValue(valuesArg.port) || candidateArg.port || snapshot?.router.port || (host ? MikrotikMapper.defaultPort(verifySsl) : undefined);
    const config: IMikrotikConfig = {
      host,
      port,
      username: this.stringValue(valuesArg.username),
      password: this.stringValue(valuesArg.password),
      verifySsl,
      protocol: MikrotikMapper.protocol(verifySsl),
      forceDhcp: this.booleanValue(valuesArg.forceDhcp) ?? false,
      arpPing: this.booleanValue(valuesArg.arpPing) ?? false,
      detectionTime: this.numberValue(valuesArg.detectionTime) || mikrotikDefaultDetectionTime,
      uniqueId: candidateArg.id || snapshot?.router.serialNumber || snapshot?.router.macAddress,
      name: candidateArg.name || snapshot?.router.name || snapshot?.router.identity || host,
      snapshot,
      metadata: {
        discoverySource: candidateArg.source,
        discoveryMetadata: candidateArg.metadata,
        upstreamPlatforms: ['device_tracker'],
        liveRouterOsApiImplemented: false,
      },
    };

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

  private snapshotFromInput(valueArg: unknown): IMikrotikSnapshot | undefined | Error {
    if (valueArg && typeof valueArg === 'object') {
      return valueArg as IMikrotikSnapshot;
    }
    const text = this.stringValue(valueArg);
    if (!text) {
      return undefined;
    }
    try {
      const parsed = JSON.parse(text) as IMikrotikSnapshot;
      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) && valueArg > 0) {
      return Math.round(valueArg);
    }
    if (typeof valueArg === 'string' && valueArg.trim()) {
      const parsed = Number(valueArg);
      return Number.isFinite(parsed) && parsed > 0 ? 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;
  }
}
