import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IDoorbirdConfig, IDoorbirdInfo, IDoorbirdSnapshot, IDoorbirdStatus, TDoorbirdProtocol } from './doorbird.types.js';
import { doorbirdDefaultHttpsPort, doorbirdDefaultPort, doorbirdDefaultTimeoutMs, doorbirdManufacturer } from './doorbird.types.js';

export class DoorbirdConfigFlow implements IConfigFlow<IDoorbirdConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IDoorbirdConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect DoorBird',
      description: 'Configure a local DoorBird HTTP endpoint discovered by zeroconf or entered manually.',
      fields: [
        { name: 'host', label: 'Host', type: 'text' },
        { name: 'port', label: 'HTTP port', type: 'number' },
        { name: 'ssl', label: 'Use HTTPS', type: 'boolean' },
        { name: 'username', label: 'Username', type: 'text', required: true },
        { name: 'password', label: 'Password', type: 'password', required: true },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'events', label: 'Events (comma separated)', type: 'text' },
      ],
      submit: async (valuesArg) => this.submit(candidateArg, valuesArg),
    };
  }

  private async submit(candidateArg: IDiscoveryCandidate, valuesArg: Record<string, unknown>): Promise<IConfigFlowStep<IDoorbirdConfig>> {
    const metadata = candidateArg.metadata || {};
    const parsed = parseEndpoint(this.stringValue(valuesArg.host) || this.stringValue(metadata.url) || candidateArg.host);
    const snapshot = snapshotValue(metadata.snapshot);
    const rawInfo = infoValue(metadata.rawInfo);
    const status = statusValue(metadata.status);
    const host = parsed?.host || this.stringValue(valuesArg.host) || candidateArg.host || snapshot?.deviceInfo.host;
    const protocol = parsed?.protocol || (this.booleanValue(valuesArg.ssl) ?? booleanMetadata(metadata, 'ssl') ? 'https' : 'http');
    const port = this.numberValue(valuesArg.port) || candidateArg.port || parsed?.port || snapshot?.deviceInfo.port || (protocol === 'https' ? doorbirdDefaultHttpsPort : doorbirdDefaultPort);
    const hasManualData = Boolean(snapshot || rawInfo || status || metadata.client);
    const username = this.stringValue(valuesArg.username) || stringMetadata(metadata, 'username');
    const password = this.stringValue(valuesArg.password) || stringMetadata(metadata, 'password');

    if (!host && !hasManualData) {
      return { kind: 'error', title: 'DoorBird setup failed', error: 'DoorBird host, injected client, snapshot, or raw info is required.' };
    }
    if (!validPort(port)) {
      return { kind: 'error', title: 'DoorBird setup failed', error: 'DoorBird port must be between 1 and 65535.' };
    }
    if (host && !hasManualData && (!username || password === undefined)) {
      return { kind: 'error', title: 'DoorBird setup failed', error: 'DoorBird username and password are required for live local HTTP setup.' };
    }

    const config: IDoorbirdConfig = {
      host,
      port,
      protocol,
      ssl: protocol === 'https',
      username,
      password,
      name: this.stringValue(valuesArg.name) || candidateArg.name || snapshot?.deviceInfo.name || stringMetadata(metadata, 'name'),
      manufacturer: candidateArg.manufacturer || snapshot?.deviceInfo.manufacturer || doorbirdManufacturer,
      model: candidateArg.model || snapshot?.deviceInfo.model,
      macAddress: candidateArg.macAddress || snapshot?.deviceInfo.macAddress || stringMetadata(metadata, 'macaddress') || stringMetadata(metadata, 'macAddress'),
      uniqueId: candidateArg.id || snapshot?.deviceInfo.id || candidateArg.macAddress || (host ? `${host}:${port}` : undefined),
      timeoutMs: doorbirdDefaultTimeoutMs,
      events: this.eventsValue(valuesArg.events) || this.eventsValue(metadata.events) || ['doorbell', 'motion'],
      snapshot,
      rawInfo,
      status,
      client: metadata.client as IDoorbirdConfig['client'],
      commandExecutor: metadata.commandExecutor as IDoorbirdConfig['commandExecutor'],
    };

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

  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;
  }

  private eventsValue(valueArg: unknown): string[] | undefined {
    if (Array.isArray(valueArg)) {
      return valueArg.map((eventArg) => this.stringValue(eventArg)).filter(Boolean) as string[];
    }
    const value = this.stringValue(valueArg);
    if (!value) {
      return undefined;
    }
    return value.split(',').map((eventArg) => eventArg.trim()).filter(Boolean);
  }
}

const parseEndpoint = (valueArg: string | undefined): { protocol: TDoorbirdProtocol; 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): IDoorbirdSnapshot | undefined => {
  return valueArg && typeof valueArg === 'object' && 'deviceInfo' in valueArg && 'cameras' in valueArg ? valueArg as IDoorbirdSnapshot : undefined;
};

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

const statusValue = (valueArg: unknown): IDoorbirdStatus | undefined => {
  return valueArg && typeof valueArg === 'object' && !Array.isArray(valueArg) ? valueArg as IDoorbirdStatus : 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;
