import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IGo2rtcConfig, TGo2rtcProtocol } from './go2rtc.types.js';
import { go2rtcDefaultApiPort, go2rtcDefaultRtspPort, go2rtcDefaultWebRtcPort } from './go2rtc.types.js';

export class Go2rtcConfigFlow implements IConfigFlow<IGo2rtcConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IGo2rtcConfig>> {
    void contextArg;
    const endpoint = endpointFromCandidate(candidateArg);
    return {
      kind: 'form',
      title: 'Connect go2rtc',
      description: 'Configure a local go2rtc HTTP API endpoint. Username and password are optional for unauthenticated local instances.',
      fields: [
        { name: 'protocol', label: 'Protocol', type: 'select', required: true, options: [{ label: 'HTTP', value: 'http' }, { label: 'HTTPS', value: 'https' }] },
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'API 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 protocol = protocolValue(valuesArg.protocol) || endpoint.protocol;
        const host = stringValue(valuesArg.host) || endpoint.host;
        const port = numberValue(valuesArg.port) || endpoint.port || go2rtcDefaultApiPort;
        if (!host) {
          return { kind: 'error', title: 'go2rtc host required', error: 'host_required' };
        }
        if (!Number.isInteger(port) || port < 1 || port > 65535) {
          return { kind: 'error', title: 'Invalid go2rtc API port', error: 'invalid_port' };
        }
        return {
          kind: 'done',
          title: 'go2rtc configured',
          config: {
            uniqueId: candidateArg.id || host,
            name: candidateArg.name || host,
            protocol,
            host,
            port,
            url: `${protocol}://${hostForUrl(host)}:${port}`,
            username: stringValue(valuesArg.username),
            password: stringValue(valuesArg.password),
            rtsp: {
              host,
              port: numberValue(candidateArg.metadata?.rtspPort) || go2rtcDefaultRtspPort,
              enabled: candidateArg.metadata?.rtspEnabled !== false,
            },
            webrtc: {
              host,
              port: numberValue(candidateArg.metadata?.webRtcPort ?? candidateArg.metadata?.webrtcPort) || go2rtcDefaultWebRtcPort,
              enabled: candidateArg.metadata?.webRtcEnabled !== false && candidateArg.metadata?.webrtcEnabled !== false,
            },
            metadata: {
              ...candidateArg.metadata,
              discoverySource: candidateArg.source,
            },
          },
        };
      },
    };
  }
}

const endpointFromCandidate = (candidateArg: IDiscoveryCandidate): { protocol: TGo2rtcProtocol; host?: string; port: number } => {
  const metadataUrl = typeof candidateArg.metadata?.url === 'string' ? candidateArg.metadata.url : undefined;
  const parsed = safeUrl(metadataUrl || candidateArg.host);
  if (parsed) {
    const protocol = parsed.protocol === 'https:' ? 'https' : 'http';
    return { protocol, host: parsed.hostname, port: parsed.port ? Number(parsed.port) : protocol === 'https' ? 443 : go2rtcDefaultApiPort };
  }
  const protocol = candidateArg.metadata?.protocol === 'https' ? 'https' : 'http';
  return { protocol, host: candidateArg.host, port: candidateArg.port || go2rtcDefaultApiPort };
};

const safeUrl = (valueArg: string | undefined): URL | undefined => {
  if (!valueArg) {
    return undefined;
  }
  try {
    return new URL(valueArg);
  } catch {
    return undefined;
  }
};

const protocolValue = (valueArg: unknown): TGo2rtcProtocol | undefined => {
  return valueArg === 'http' || valueArg === 'https' ? valueArg : undefined;
};

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

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

const hostForUrl = (hostArg: string): string => hostArg.includes(':') && !hostArg.startsWith('[') ? `[${hostArg}]` : hostArg;
