/**
 * Cliente al multiagent-supervisor (servidor IA).
 * Variables: SUPERVISOR_BASE_URL, SUPERVISOR_DASHBOARD_TOKEN
 */
const BASE = (process.env.SUPERVISOR_BASE_URL || process.env.REMOTE_AI_SERVER || "http://192.168.1.16:8787").replace(/\/$/, "");
const TOKEN = process.env.SUPERVISOR_DASHBOARD_TOKEN || "";
const PROJECT_ID = "captajaus";

function headers(): Record<string, string> {
  const h: Record<string, string> = { Accept: "application/json", "Content-Type": "application/json" };
  if (TOKEN) h["X-Supervisor-Token"] = TOKEN;
  return h;
}

async function postJson<T>(path: string, body: unknown, timeoutMs = 25000): Promise<{ ok: boolean; status: number; data: T | null }> {
  const controller = new AbortController();
  const t = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const res = await fetch(`${BASE}${path}`, {
      method: "POST",
      headers: headers(),
      body: JSON.stringify(body),
      signal: controller.signal,
    });
    const text = await res.text();
    let data: T | null = null;
    try {
      data = text ? (JSON.parse(text) as T) : null;
    } catch {
      data = null;
    }
    return { ok: res.ok, status: res.status, data };
  } finally {
    clearTimeout(t);
  }
}

async function getJson<T>(path: string, timeoutMs = 12000): Promise<{ ok: boolean; status: number; data: T | null }> {
  const controller = new AbortController();
  const t = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const res = await fetch(`${BASE}${path}`, { headers: headers(), signal: controller.signal });
    const text = await res.text();
    let data: T | null = null;
    try {
      data = text ? (JSON.parse(text) as T) : null;
    } catch {
      data = null;
    }
    return { ok: res.ok, status: res.status, data };
  } finally {
    clearTimeout(t);
  }
}

export function supervisorConfig() {
  return {
    baseUrl: BASE,
    hasToken: Boolean(TOKEN),
    projectId: PROJECT_ID,
    bridgeUrl: process.env.CURSOR_BRIDGE_URL || "http://100.78.198.98:8095",
  };
}

export async function getSupervisorHealth() {
  return getJson<{ status?: string }>("/health");
}

export async function getRagStatus() {
  return getJson(`/api/rag/status?project=${encodeURIComponent(PROJECT_ID)}`);
}

export async function recommendTask(task: string, agent?: string) {
  return postJson("/api/agent-templates/recommend", {
    task,
    project: PROJECT_ID,
    agent: agent || undefined,
    top_k: 3,
  });
}

export async function dispatchChat(message: string, agent = "ops") {
  return postJson("/api/chat", {
    message,
    project: PROJECT_ID,
    agent,
    mode: "agent",
  });
}

export function buildBridgeDeepLink(prompt: string, autoSend = true): string {
  const bridge = (process.env.CURSOR_BRIDGE_URL || "http://100.78.198.98:8095").replace(/\/$/, "");
  const q = new URLSearchParams({
    project: "captajaus",
    prompt: prompt.slice(0, 2000),
    propose: "1",
    continue: "1",
  });
  if (autoSend) q.set("autosend", "1");
  return `${bridge}/?${q.toString()}`;
}

export async function ingestRagTexts(texts: { text: string; id?: string; type?: string }[]) {
  return postJson("/api/rag/ingest", {
    project: PROJECT_ID,
    texts: texts.map((t) => ({
      text: t.text,
      id: t.id || `captajaus-insight-${Date.now()}`,
      type: t.type || "operational_insight",
    })),
  });
}

export async function ingestProjectDocs() {
  return postJson("/api/rag/ingest", {
    project: PROJECT_ID,
    include_source: true,
  });
}
