import { execSync } from 'child_process';
import fs from 'fs';

function normalizeUrl(input: string): string {
  const trimmed = input.trim().replace(/\/+$/, '');
  if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
    return trimmed;
  }
  return `http://${trimmed}`;
}

function detectWslGatewayOllamaUrl(): string | null {
  try {
    if (process.platform !== 'linux') return null;
    const version = fs.readFileSync('/proc/version', 'utf-8').toLowerCase();
    if (!version.includes('microsoft')) return null;

    const gw = execSync("ip route show default | awk '{print $3}' | head -1", {
      encoding: 'utf-8',
      stdio: ['ignore', 'pipe', 'ignore'],
    }).trim();
    if (!gw) return null;
    return `http://${gw}:11434`;
  } catch {
    return null;
  }
}

/**
 * Resolve the Ollama base URL from environment variables with WSL2 fallback.
 *
 * Priority:
 * 1. `OLLAMA_URL` or `OLLAMA_HOST` env var (explicit config)
 * 2. WSL2 gateway IP (Windows-hosted Ollama detected via /proc/version)
 * 3. `http://localhost:11434` (default)
 *
 * @param env - Environment variables object (defaults to `process.env`)
 */
export function resolveOllamaUrl(env: Record<string, string | undefined> = process.env): string {
  const explicit = env.OLLAMA_URL || env.OLLAMA_HOST;
  if (explicit) return normalizeUrl(explicit);

  const inferred = detectWslGatewayOllamaUrl();
  if (inferred) return inferred;

  return 'http://localhost:11434';
}
