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

const explicit = process.env.OLLAMA_URL || process.env.OLLAMA_HOST;
const inferred = detectWslGatewayOllamaUrl();

// Priority:
// 1) OLLAMA_URL / OLLAMA_HOST (explicit config)
// 2) WSL2 gateway (Windows-hosted Ollama)
// 3) localhost default
export const OLLAMA_URL = explicit
  ? normalizeUrl(explicit)
  : inferred || 'http://localhost:11434';
