import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import { normalizeXiaomiMiioToken } from './xiaomi_miio.discovery.js';
import type { IXiaomiMiioConfig, IXiaomiMiioSnapshot } from './xiaomi_miio.types.js';

const defaultMiioPort = 54321;

export class XiaomiMiioConfigFlow implements IConfigFlow<IXiaomiMiioConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IXiaomiMiioConfig>> {
    void contextArg;
    const defaults = this.defaultsFromCandidate(candidateArg);
    return {
      kind: 'form',
      title: 'Connect Xiaomi Home device',
      description: 'Provide the local host, 32-character Miio token, model/name, and optional snapshot JSON. Live encrypted UDP probing is not performed by this TypeScript port.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'token', label: 'Miio token', type: 'password', required: true },
        { name: 'model', label: 'Model', type: 'text', required: true },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'snapshotJson', label: 'Snapshot JSON', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || defaults.host;
        const token = normalizeXiaomiMiioToken(valuesArg.token) || defaults.token;
        const model = this.stringValue(valuesArg.model) || defaults.model;
        const name = this.stringValue(valuesArg.name) || defaults.name || model;
        const snapshot = this.snapshotValue(valuesArg.snapshotJson, defaults.snapshot);

        if (!host) {
          return { kind: 'error', title: 'Invalid Xiaomi Miio host', error: 'Host is required.' };
        }
        if (!token) {
          return { kind: 'error', title: 'Invalid Xiaomi Miio token', error: 'Token must be 32 hexadecimal characters.' };
        }
        if (!model) {
          return { kind: 'error', title: 'Invalid Xiaomi Miio model', error: 'Model is required.' };
        }
        if (snapshot === false) {
          return { kind: 'error', title: 'Invalid Xiaomi Miio snapshot', error: 'Snapshot JSON must be a JSON object.' };
        }

        return {
          kind: 'done',
          title: 'Xiaomi Home device configured',
          config: {
            host,
            port: defaults.port || defaultMiioPort,
            token,
            model,
            name: name || model,
            macAddress: defaults.macAddress,
            deviceId: defaults.deviceId,
            snapshot: snapshot || undefined,
          },
        };
      },
    };
  }

  private defaultsFromCandidate(candidateArg: IDiscoveryCandidate): { host?: string; port?: number; token?: string; model?: string; name?: string; macAddress?: string; deviceId?: string; snapshot?: IXiaomiMiioSnapshot } {
    const metadata = candidateArg.metadata || {};
    return {
      host: candidateArg.host,
      port: candidateArg.port,
      token: normalizeXiaomiMiioToken(metadata.token),
      model: candidateArg.model || this.stringValue(metadata.model),
      name: candidateArg.name || this.stringValue(metadata.name),
      macAddress: candidateArg.macAddress || this.stringValue(metadata.macAddress),
      deviceId: candidateArg.id || this.stringValue(metadata.deviceId),
      snapshot: this.isSnapshot(metadata.snapshot) ? metadata.snapshot : undefined,
    };
  }

  private snapshotValue(valueArg: unknown, fallbackArg?: IXiaomiMiioSnapshot): IXiaomiMiioSnapshot | undefined | false {
    if (valueArg === undefined || valueArg === null || valueArg === '') {
      return fallbackArg;
    }
    if (this.isSnapshot(valueArg)) {
      return valueArg;
    }
    if (typeof valueArg !== 'string') {
      return false;
    }
    try {
      const parsed = JSON.parse(valueArg) as unknown;
      return this.isRecord(parsed) ? parsed as unknown as IXiaomiMiioSnapshot : false;
    } catch {
      return false;
    }
  }

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;
  }

  private isSnapshot(valueArg: unknown): valueArg is IXiaomiMiioSnapshot {
    return this.isRecord(valueArg);
  }

  private isRecord(valueArg: unknown): valueArg is Record<string, unknown> {
    return typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg);
  }
}
