// API Constants
export const API_STATE = '/api/state';
export const API_STREAM = '/api/stream';
export const API_DISMISS = '/api/dismiss/';
export const API_DISMISS_DEAD = '/api/dismiss-dead';
export const API_RESPOND = '/api/respond/';
export const API_CONVERSATION = '/api/conversation/';
export const API_SKILLS = '/api/skills';
export const API_SPAWN = '/api/spawn';
export const API_PROJECTS = '/api/projects';
export const API_PROJECTS_REFRESH = '/api/projects/refresh';
export const API_HEALTH = '/api/health';
export const POLL_MS = 3000;
export const API_TIMEOUT_MS = 10000;

// Fetch with timeout to prevent hanging requests
export async function fetchWithTimeout(url, options = {}, timeoutMs = API_TIMEOUT_MS) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const response = await fetch(url, { ...options, signal: controller.signal });
    return response;
  } finally {
    clearTimeout(timeoutId);
  }
}

// Fetch autocomplete skills config for an agent type
export async function fetchSkills(agent) {
  const url = `${API_SKILLS}?agent=${encodeURIComponent(agent)}`;
  try {
    const response = await fetchWithTimeout(url);
    if (!response.ok) return null;
    return await response.json();
  } catch {
    // Network error, timeout, or JSON parse failure - graceful degradation
    return null;
  }
}
