import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IFullyKioskConfig, IFullyKioskDeviceInfo, IFullyKioskSettings, IFullyKioskSnapshot, TFullyKioskProtocol } from './fully_kiosk.types.js';
import { fullyKioskDefaultPort, fullyKioskDefaultTimeoutMs } from './fully_kiosk.types.js';

export class FullyKioskConfigFlow implements IConfigFlow<IFullyKioskConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IFullyKioskConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Fully Kiosk Browser',
      description: 'Configure a local Fully Kiosk REST endpoint. Remote Admin must be enabled in Fully Kiosk and live control requires the Remote Admin password.',
      fields: [
        { name: 'host', label: 'Host or URL', type: 'text' },
        { name: 'port', label: 'Remote Admin port', type: 'number' },
        { name: 'ssl', label: 'Use HTTPS', type: 'boolean' },
        { name: 'verifySsl', label: 'Verify TLS certificate', type: 'boolean' },
        { name: 'password', label: 'Remote Admin password', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => this.submit(candidateArg, valuesArg),
    };
  }

  private async submit(candidateArg: IDiscoveryCandidate, valuesArg: Record<string, unknown>): Promise<IConfigFlowStep<IFullyKioskConfig>> {
    const metadata = candidateArg.metadata || {};
    const parsed = parseEndpoint(this.stringValue(valuesArg.host) || stringMetadata(metadata, 'url') || candidateArg.host);
    const snapshot = snapshotValue(metadata.snapshot);
    const deviceInfo = deviceInfoValue(metadata.deviceInfo);
    const settings = settingsValue(metadata.settings);
    const host = parsed?.host || this.stringValue(valuesArg.host) || candidateArg.host || snapshot?.host || snapshot?.deviceInfo.ip4;
    const protocol = parsed?.protocol || (this.booleanValue(valuesArg.ssl) ?? booleanMetadata(metadata, 'ssl') ? 'https' : 'http');
    const port = this.numberValue(valuesArg.port) || candidateArg.port || parsed?.port || snapshot?.port || fullyKioskDefaultPort;
    const password = this.stringValue(valuesArg.password) || stringMetadata(metadata, 'password');
    const hasManualData = Boolean(snapshot || deviceInfo || settings || metadata.client);

    if (!host && !hasManualData) {
      return { kind: 'error', title: 'Fully Kiosk setup failed', error: 'Fully Kiosk setup requires a host, injected client, snapshot, or device info.' };
    }
    if (!validPort(port)) {
      return { kind: 'error', title: 'Fully Kiosk setup failed', error: 'Fully Kiosk port must be between 1 and 65535.' };
    }
    if (host && !password && !metadata.client) {
      return { kind: 'error', title: 'Fully Kiosk setup failed', error: 'Fully Kiosk live local REST access requires the Remote Admin password.' };
    }

    return {
      kind: 'done',
      title: 'Fully Kiosk configured',
      config: {
        host,
        port,
        protocol,
        ssl: protocol === 'https',
        verifySsl: this.booleanValue(valuesArg.verifySsl) ?? booleanMetadata(metadata, 'verifySsl') ?? false,
        password,
        name: this.stringValue(valuesArg.name) || candidateArg.name || snapshot?.name || deviceInfo?.deviceName,
        uniqueId: candidateArg.id || snapshot?.uniqueId || deviceInfo?.deviceID || deviceInfo?.deviceId || candidateArg.macAddress || (host ? `${host}:${port}` : undefined),
        macAddress: candidateArg.macAddress || snapshot?.macAddress || deviceInfo?.Mac || deviceInfo?.mac || stringMetadata(metadata, 'macAddress') || stringMetadata(metadata, 'macaddress'),
        manufacturer: candidateArg.manufacturer || snapshot?.deviceInfo.deviceManufacturer || deviceInfo?.deviceManufacturer || 'Fully Kiosk',
        model: candidateArg.model || snapshot?.deviceInfo.deviceModel || deviceInfo?.deviceModel,
        timeoutMs: fullyKioskDefaultTimeoutMs,
        snapshot,
        deviceInfo,
        settings,
        client: metadata.client as IFullyKioskConfig['client'],
        commandExecutor: metadata.commandExecutor as IFullyKioskConfig['commandExecutor'],
      },
    };
  }

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim().replace(/\/$/, '') : 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') {
      const normalized = valueArg.trim().toLowerCase();
      if (['true', 'yes', 'on', '1'].includes(normalized)) {
        return true;
      }
      if (['false', 'no', 'off', '0'].includes(normalized)) {
        return false;
      }
    }
    return undefined;
  }
}

const parseEndpoint = (valueArg: string | undefined): { protocol: TFullyKioskProtocol; host: string; port?: number } | undefined => {
  if (!valueArg || !/^[a-z][a-z0-9+.-]*:\/\//i.test(valueArg)) {
    return undefined;
  }
  try {
    const url = new URL(valueArg);
    return {
      protocol: url.protocol === 'https:' ? 'https' : 'http',
      host: url.hostname,
      port: url.port ? Number(url.port) : undefined,
    };
  } catch {
    return undefined;
  }
};

const snapshotValue = (valueArg: unknown): IFullyKioskSnapshot | undefined => {
  return valueArg && typeof valueArg === 'object' && 'deviceInfo' in valueArg && 'settings' in valueArg ? valueArg as IFullyKioskSnapshot : undefined;
};

const deviceInfoValue = (valueArg: unknown): IFullyKioskDeviceInfo | undefined => {
  return valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg) ? valueArg as IFullyKioskDeviceInfo : undefined;
};

const settingsValue = (valueArg: unknown): IFullyKioskSettings | undefined => {
  return valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg) ? valueArg as IFullyKioskSettings : undefined;
};

const stringMetadata = (metadataArg: Record<string, unknown>, keyArg: string): string | undefined => {
  const value = metadataArg[keyArg];
  return typeof value === 'string' && value.trim() ? value.trim() : undefined;
};

const booleanMetadata = (metadataArg: Record<string, unknown>, keyArg: string): boolean | undefined => {
  const value = metadataArg[keyArg];
  return typeof value === 'boolean' ? value : undefined;
};

const validPort = (valueArg: number): boolean => Number.isInteger(valueArg) && valueArg > 0 && valueArg <= 65535;
