/**
 * Centralized endpoint configuration for Agent UI
 * Automatically detects HTTPS/Traefik and uses appropriate protocols
 * Supports Tauri mode where all URLs resolve against a configured server
 */

import { isTauri, getServerUrl } from '@/lib/tauri'

// Detect if running over HTTPS (behind Traefik)
export const isSecure = window.location.protocol === 'https:'

// WebSocket protocol based on HTTP protocol
export const wsProtocol = isSecure ? 'wss:' : 'ws:'

// Base hostname
export const hostname = window.location.hostname

// Build WebSocket URL based on environment
function buildWsUrl(securePath: string, devPort: number): string {
  if (isSecure) {
    // Behind Traefik - use path-based routing
    return `${wsProtocol}//${hostname}${securePath}`
  }
  // Development - direct port access
  return `${wsProtocol}//${hostname}:${devPort}`
}

// Build HTTP URL for services
function buildHttpUrl(securePath: string, devPort: number): string {
  if (isSecure) {
    return `https://${hostname}${securePath}`
  }
  return `http://${hostname}:${devPort}`
}

// Static endpoint configuration (used in web mode)
export const endpoints = {
  // Terminal WebSocket
  terminal: buildWsUrl('/ws/terminal', 4103),

  // Git WebSocket (realtime notifications, separate from terminal)
  git: buildWsUrl('/ws/git', 4105),

  // Claude status WebSocket (same backend as terminal)
  claudeStatus: buildWsUrl('/ws/status', 4103),

  // Whisper WebSocket - voice transcription
  whisper: buildWsUrl('/ws/whisper', 4104),

  // WebMCP WebSocket
  webmcp: buildWsUrl('/ws/mcp', 4102),

  // WebMCP HTTP API (for token requests)
  webmcpHttp: buildHttpUrl('/mcp', 4102),

  // Torch WebSocket (multi-browser sync) - same port as git
  torch: buildWsUrl('/ws/git', 4105),

  // API base URL (Vite proxy handles /api in dev)
  api: '/api'
}

/**
 * Resolve endpoints dynamically.
 * In Tauri mode, builds WebSocket/HTTP URLs against the configured server.
 * In web mode, returns the static endpoints.
 */
export function resolveEndpoints() {
  if (!isTauri) return endpoints

  const serverUrl = getServerUrl()
  if (!serverUrl) return endpoints

  // Parse server URL to get host and protocol
  let url: URL
  try {
    url = new URL(serverUrl)
  } catch {
    return endpoints
  }

  const secure = url.protocol === 'https:'
  const wsProto = secure ? 'wss:' : 'ws:'
  const host = url.host // includes port if non-standard

  function tauriBuildWs(securePath: string, devPort: number): string {
    if (secure) {
      return `${wsProto}//${host}${securePath}`
    }
    // In Tauri dev, use the server host with specific ports
    const baseHost = url.hostname
    return `${wsProto}//${baseHost}:${devPort}`
  }

  function tauriBuildHttp(securePath: string, devPort: number): string {
    if (secure) {
      return `${url.protocol}//${host}${securePath}`
    }
    const baseHost = url.hostname
    return `http://${baseHost}:${devPort}`
  }

  return {
    terminal: tauriBuildWs('/ws/terminal', 4103),
    git: tauriBuildWs('/ws/git', 4105),
    claudeStatus: tauriBuildWs('/ws/status', 4103),
    whisper: tauriBuildWs('/ws/whisper', 4104),
    webmcp: tauriBuildWs('/ws/mcp', 4102),
    webmcpHttp: tauriBuildHttp('/mcp', 4102),
    torch: tauriBuildWs('/ws/git', 4105),
    api: `${serverUrl}/api`
  }
}

/** Get the API base URL (for use in Tauri and web) */
export function getApiBase(): string {
  if (!isTauri) return '/api'
  const serverUrl = getServerUrl()
  return serverUrl ? `${serverUrl}/api` : '/api'
}

// Agent terminal helpers
export function agentTerminalUrl(agentId: string): string {
  const base = resolveEndpoints().terminal
  const sep = base.includes('?') ? '&' : '?'
  return `${base}${sep}session=agent-${agentId}`
}

export function terminalApiUrl(path: string): string {
  if (isTauri) {
    const serverUrl = getServerUrl()
    if (serverUrl) {
      const url = new URL(serverUrl)
      const secure = url.protocol === 'https:'
      if (secure) return `https://${url.host}/ws/terminal${path}`
      return `http://${url.hostname}:4103${path}`
    }
  }
  if (isSecure) return `https://${hostname}/ws/terminal${path}`
  return `http://${hostname}:4103${path}`
}

// Debug logging
console.log('[Endpoints]', isTauri ? 'Tauri mode' : (isSecure ? 'HTTPS/Traefik mode' : 'Development mode'), endpoints)
