import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import { AsuswrtMapper } from './asuswrt.mapper.js';
import type { IAsuswrtConfig, IAsuswrtSnapshot, TAsuswrtMode, TAsuswrtProtocol } from './asuswrt.types.js';
import { asuswrtDefaultConsiderHomeSeconds, asuswrtDefaultDnsmasqPath, asuswrtDefaultInterface } from './asuswrt.types.js';

export class AsuswrtConfigFlow implements IConfigFlow<IAsuswrtConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IAsuswrtConfig>> {
    void contextArg;
    const metadata = candidateArg.metadata || {};
    const protocol = this.protocolValue(metadata.protocol) || 'https';
    return {
      kind: 'form',
      title: 'Connect ASUSWRT router',
      description: 'Provide the local ASUSWRT router endpoint. Snapshot/manual data is supported directly; SSH/Telnet live success is not assumed without an injected executor or native client.',
      fields: [
        { name: 'host', label: candidateArg.host ? `Host (${candidateArg.host})` : 'Host', type: 'text', required: true },
        { name: 'port', label: `Port (${candidateArg.port || AsuswrtMapper.defaultPort(protocol)})`, type: 'number' },
        { name: 'protocol', label: 'Protocol', type: 'select', options: [
          { label: 'HTTPS', value: 'https' },
          { label: 'HTTP', value: 'http' },
          { label: 'SSH', value: 'ssh' },
          { label: 'Telnet', value: 'telnet' },
        ] },
        { name: 'username', label: 'Username', type: 'text' },
        { name: 'password', label: 'Password', type: 'password' },
        { name: 'sshKey', label: 'SSH key path', type: 'text' },
        { name: 'mode', label: 'Router mode', type: 'select', options: [
          { label: 'Router', value: 'router' },
          { label: 'Access Point', value: 'ap' },
        ] },
        { name: 'interface', label: `Interface (${asuswrtDefaultInterface})`, type: 'text' },
        { name: 'trackUnknown', label: 'Track unknown devices', type: 'boolean' },
        { 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<IAsuswrtConfig>> {
    const snapshot = this.snapshotFromInput(valuesArg.snapshotJson || candidateArg.metadata?.snapshot);
    if (snapshot instanceof Error) {
      return { kind: 'error', title: 'Invalid ASUSWRT snapshot', error: snapshot.message };
    }

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

    const port = this.numberValue(valuesArg.port) || candidateArg.port || snapshot?.router.port || (host ? AsuswrtMapper.defaultPort(protocol) : undefined);
    const config: IAsuswrtConfig = {
      host,
      port,
      protocol,
      username: this.stringValue(valuesArg.username),
      password: this.stringValue(valuesArg.password),
      sshKey: this.stringValue(valuesArg.sshKey),
      mode: this.modeValue(valuesArg.mode) || this.modeValue(candidateArg.metadata?.mode) || snapshot?.router.mode || 'router',
      interface: this.stringValue(valuesArg.interface) || asuswrtDefaultInterface,
      dnsmasq: asuswrtDefaultDnsmasqPath,
      requireIp: true,
      trackUnknown: valuesArg.trackUnknown === true,
      considerHomeSeconds: asuswrtDefaultConsiderHomeSeconds,
      uniqueId: candidateArg.id || snapshot?.router.labelMac || snapshot?.router.macAddress,
      name: candidateArg.name || snapshot?.router.name,
      snapshot,
      metadata: {
        discoverySource: candidateArg.source,
        discoveryMetadata: candidateArg.metadata,
        liveSshTelnetImplemented: false,
      },
    };

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

  private snapshotFromInput(valueArg: unknown): IAsuswrtSnapshot | undefined | Error {
    if (valueArg && typeof valueArg === 'object') {
      return valueArg as IAsuswrtSnapshot;
    }
    const text = this.stringValue(valueArg);
    if (!text) {
      return undefined;
    }
    try {
      const parsed = JSON.parse(text) as IAsuswrtSnapshot;
      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 protocolValue(valueArg: unknown): TAsuswrtProtocol | undefined {
    return valueArg === 'http' || valueArg === 'https' || valueArg === 'ssh' || valueArg === 'telnet' ? valueArg : undefined;
  }

  private modeValue(valueArg: unknown): TAsuswrtMode | undefined {
    return valueArg === 'router' || valueArg === 'ap' ? valueArg : undefined;
  }
}
