import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import { androidtvDefaultPort } from './androidtv.constants.js';
import type { IAndroidtvConfig, TAndroidtvDeviceClass } from './androidtv.types.js';

export class AndroidtvConfigFlow implements IConfigFlow<IAndroidtvConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IAndroidtvConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Android Debug Bridge',
      description: 'Configure an Android TV or Fire TV ADB host. Port defaults to 5555.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'deviceName', label: 'Device 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', title: 'Android TV configuration failed', error: 'Host is required.' };
        }
        const port = this.numberValue(valuesArg.port) || candidateArg.port || androidtvDefaultPort;
        const deviceName = this.stringValue(valuesArg.deviceName) || candidateArg.name;
        const model = this.stringValue(valuesArg.model) || candidateArg.model;
        return {
          kind: 'done',
          title: 'Android Debug Bridge configured',
          config: {
            host,
            port,
            deviceName,
            model,
            manufacturer: candidateArg.manufacturer,
            deviceClass: this.deviceClass(candidateArg),
            deviceInfo: {
              name: deviceName,
              host,
              port,
              model,
              manufacturer: candidateArg.manufacturer,
              serialNumber: candidateArg.serialNumber,
              deviceClass: this.deviceClass(candidateArg),
            },
          },
        };
      },
    };
  }

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

  private numberValue(valueArg: unknown): number | undefined {
    return typeof valueArg === 'number' && Number.isFinite(valueArg) && valueArg > 0 ? valueArg : undefined;
  }

  private deviceClass(candidateArg: IDiscoveryCandidate): TAndroidtvDeviceClass {
    const hintedClass = candidateArg.metadata?.deviceClass;
    if (hintedClass === 'firetv' || hintedClass === 'androidtv') {
      return hintedClass;
    }
    const manufacturer = candidateArg.manufacturer?.toLowerCase() || '';
    const model = candidateArg.model?.toLowerCase() || '';
    return manufacturer.includes('amazon') || model.includes('fire tv') || model.includes('firetv') ? 'firetv' : 'androidtv';
  }
}
