import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IOnvifConfig } from './onvif.types.js';
import { onvifDefaultPort } from './onvif.types.js';

export class OnvifConfigFlow implements IConfigFlow<IOnvifConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IOnvifConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect ONVIF Camera',
      description: 'Provide ONVIF device service connection details. Username and password may be empty for cameras that allow anonymous ONVIF access.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number', required: true },
        { name: 'username', label: 'Username', type: 'text', required: false },
        { name: 'password', label: 'Password', type: 'password', required: false },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host;
        const port = this.portValue(valuesArg.port) || candidateArg.port || onvifDefaultPort;
        if (!host) {
          return { kind: 'error', title: 'ONVIF host required', error: 'host_required' };
        }
        if (port < 1 || port > 65535) {
          return { kind: 'error', title: 'Invalid ONVIF port', error: 'invalid_port' };
        }
        return {
          kind: 'done',
          title: 'ONVIF camera configured',
          config: {
            id: candidateArg.id,
            name: candidateArg.name || host,
            host,
            port,
            username: this.stringValue(valuesArg.username) || '',
            password: this.stringValue(valuesArg.password) || '',
            transport: candidateArg.metadata?.transport === 'https' ? 'https' : 'http',
            discovery: {
              source: candidateArg.metadata?.discoveryProtocol === 'ws-discovery' ? 'ws-discovery' : candidateArg.source === 'mdns' ? 'mdns' : 'manual',
              id: candidateArg.id,
              name: candidateArg.name,
              host,
              port,
              manufacturer: candidateArg.manufacturer,
              model: candidateArg.model,
              serialNumber: candidateArg.serialNumber,
              macAddress: candidateArg.macAddress,
              metadata: candidateArg.metadata,
            },
          },
        };
      },
    };
  }

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

  private portValue(valueArg: unknown): number | undefined {
    if (typeof valueArg === 'number' && Number.isInteger(valueArg)) {
      return valueArg;
    }
    if (typeof valueArg === 'string' && valueArg.trim()) {
      const parsed = Number(valueArg);
      return Number.isInteger(parsed) ? parsed : undefined;
    }
    return undefined;
  }
}
