import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IPiHoleConfig, IPiHoleSnapshot, TPiHoleApiVersion } from './pi_hole.types.js';
import { piHoleDefaultLocation, piHoleDefaultName, piHoleDefaultPort, piHoleDefaultTimeoutMs } from './pi_hole.types.js';

export class PiHoleConfigFlow implements IConfigFlow<IPiHoleConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IPiHoleConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Pi-hole',
      description: 'Configure a local Pi-hole HTTP API endpoint. Runtime writes are only reported successful after a real HTTP call or an explicit command executor.',
      fields: [
        { name: 'host', label: 'Host or URL', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'location', label: 'Admin location', type: 'text' },
        { name: 'apiKey', label: 'App password or API key', type: 'password', required: true },
        { name: 'ssl', label: 'Use HTTPS', type: 'boolean' },
        { name: 'verifySsl', label: 'Verify TLS certificate', type: 'boolean' },
        { name: 'apiVersion', label: 'API version', type: 'select', options: [
          { label: 'Auto (v6 then v5)', value: 'auto' },
          { label: 'v6', value: '6' },
          { label: 'v5', value: '5' },
        ] },
      ],
      submit: async (valuesArg) => this.submit(candidateArg, valuesArg),
    };
  }

  private async submit(candidateArg: IDiscoveryCandidate, valuesArg: Record<string, unknown>): Promise<IConfigFlowStep<IPiHoleConfig>> {
    const metadata = candidateArg.metadata || {};
    const parsed = parseHostInput(this.stringValue(valuesArg.host) || candidateArg.host || this.stringValue(metadata.url) || '');
    const host = parsed.host || candidateArg.host;
    const snapshot = this.snapshotValue(metadata.snapshot);
    const rawData = this.recordValue(metadata.rawData);
    const port = this.numberValue(valuesArg.port) || parsed.port || candidateArg.port || piHoleDefaultPort;
    const ssl = this.booleanValue(valuesArg.ssl) ?? parsed.ssl ?? this.booleanValue(metadata.ssl) ?? false;
    const verifySsl = this.booleanValue(valuesArg.verifySsl) ?? this.booleanValue(metadata.verifySsl) ?? true;
    const location = this.stringValue(valuesArg.location) || parsed.location || this.stringValue(metadata.location) || piHoleDefaultLocation;
    const apiKey = this.stringValue(valuesArg.apiKey) || this.stringValue(metadata.apiKey) || this.stringValue(metadata.password);
    const apiVersion = this.apiVersionValue(valuesArg.apiVersion) || this.apiVersionValue(metadata.apiVersion);

    if (!host && !snapshot && !rawData) {
      return { kind: 'error', title: 'Pi-hole setup failed', error: 'Pi-hole setup requires a host, URL, or snapshot/manual data.' };
    }
    if (!this.validPort(port)) {
      return { kind: 'error', title: 'Pi-hole setup failed', error: 'Pi-hole port must be an integer between 1 and 65535.' };
    }
    if (host && !apiKey) {
      return { kind: 'error', title: 'Pi-hole setup failed', error: 'Pi-hole App password or API key is required for HTTP API access.' };
    }

    return {
      kind: 'done',
      title: 'Pi-hole configured',
      config: {
        host,
        port,
        ssl,
        verifySsl,
        location,
        apiKey,
        apiVersion,
        name: this.stringValue(valuesArg.name) || candidateArg.name || this.stringValue(metadata.name) || piHoleDefaultName,
        uniqueId: candidateArg.id || (host ? `${host}:${port}` : undefined),
        timeoutMs: piHoleDefaultTimeoutMs,
        snapshot,
        rawData,
      },
    };
  }

  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 (valueArg.toLowerCase() === 'true') return true;
      if (valueArg.toLowerCase() === 'false') return false;
    }
    return undefined;
  }

  private apiVersionValue(valueArg: unknown): TPiHoleApiVersion | undefined {
    const value = typeof valueArg === 'number' ? String(valueArg) : this.stringValue(valueArg);
    if (value === '5' || value === '6') {
      return Number(value) as TPiHoleApiVersion;
    }
    return undefined;
  }

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

  private snapshotValue(valueArg: unknown): IPiHoleSnapshot | undefined {
    const record = this.recordValue(valueArg);
    return record && 'statistics' in record && 'status' in record ? record as unknown as IPiHoleSnapshot : undefined;
  }

  private recordValue(valueArg: unknown): Record<string, unknown> | undefined {
    return typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg) ? valueArg as Record<string, unknown> : undefined;
  }
}

const parseHostInput = (valueArg: string): { host?: string; port?: number; ssl?: boolean; location?: string } => {
  const value = valueArg.trim();
  if (!value) {
    return {};
  }
  if (!value.includes('://')) {
    const hostPort = value.match(/^([^/:]+):(\d+)$/);
    return hostPort ? { host: hostPort[1], port: Number(hostPort[2]) } : { host: value };
  }
  try {
    const parsed = new URL(value);
    const location = locationFromPath(parsed.pathname);
    return {
      host: parsed.hostname,
      port: parsed.port ? Number(parsed.port) : undefined,
      ssl: parsed.protocol === 'https:',
      location,
    };
  } catch {
    return {};
  }
};

const locationFromPath = (pathArg: string): string | undefined => {
  const parts = pathArg.split('/').filter(Boolean);
  if (!parts.length || parts[0] === 'api') {
    return undefined;
  }
  return parts[0];
};
