import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IBraviatvConfig } from './braviatv.types.js';

export class BraviatvConfigFlow implements IConfigFlow<IBraviatvConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IBraviatvConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Sony Bravia TV',
      description: 'Configure the local Sony Bravia REST/IRCC endpoint. This native port supports PSK authentication for live control; PIN pairing/cookie auth is reported as unsupported.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'HTTP port', type: 'number' },
        { name: 'useSsl', label: 'Use HTTPS', type: 'boolean' },
        { name: 'psk', label: 'Pre-shared key (PSK)', type: 'password' },
        { name: 'pin', label: 'PIN (pairing not implemented)', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'model', label: 'Model', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host;
        if (!host) {
          return { kind: 'error', error: 'Sony Bravia TV host is required.' };
        }

        const psk = this.stringValue(valuesArg.psk) || this.stringMetadata(candidateArg, 'psk');
        const pin = this.stringValue(valuesArg.pin);
        if (pin && !psk) {
          return { kind: 'error', error: 'Sony Bravia TV PIN pairing/cookie authentication is not implemented in this native TypeScript port. Configure a PSK instead.' };
        }

        const useSsl = this.booleanValue(valuesArg.useSsl) ?? this.booleanMetadata(candidateArg, 'useSsl') ?? false;
        return {
          kind: 'done',
          title: 'Sony Bravia TV configured',
          config: {
            host,
            port: this.numberValue(valuesArg.port) || candidateArg.port || (useSsl ? 443 : 80),
            useSsl,
            psk,
            pin,
            usePsk: Boolean(psk),
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            model: this.stringValue(valuesArg.model) || candidateArg.model,
            manufacturer: candidateArg.manufacturer || 'Sony',
            macAddress: candidateArg.macAddress,
            serialNumber: candidateArg.serialNumber,
            cid: candidateArg.id || this.stringMetadata(candidateArg, 'cid'),
            scalarWebApiBaseUrl: this.stringMetadata(candidateArg, 'scalarWebApiBaseUrl'),
          },
        };
      },
    };
  }

  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 valueArg;
    }
    if (typeof valueArg === 'string' && valueArg.trim()) {
      const value = Number(valueArg);
      return Number.isFinite(value) ? value : undefined;
    }
    return undefined;
  }

  private booleanValue(valueArg: unknown): boolean | undefined {
    return typeof valueArg === 'boolean' ? valueArg : undefined;
  }

  private stringMetadata(candidateArg: IDiscoveryCandidate, keyArg: string): string | undefined {
    const value = candidateArg.metadata?.[keyArg];
    return typeof value === 'string' && value ? value : undefined;
  }

  private booleanMetadata(candidateArg: IDiscoveryCandidate, keyArg: string): boolean | undefined {
    const value = candidateArg.metadata?.[keyArg];
    return typeof value === 'boolean' ? value : undefined;
  }
}
