// relay/lib/cortex.js
import fetch from "node-fetch";

const REFLECT_URL = process.env.CORTEX_URL || "http://localhost:7081/reflect";
const INGEST_URL  = process.env.CORTEX_URL_INGEST || "http://localhost:7081/ingest";

export async function reflectWithCortex(userInput, memories = []) {
  const body = { prompt: userInput, memories };
  try {
    const res = await fetch(REFLECT_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
      timeout: 120000,
    });

    const rawText = await res.text();
	console.log("🔎 [Cortex-Debug] rawText from /reflect →", rawText.slice(0, 300));
    if (!res.ok) {
      throw new Error(`HTTP ${res.status} — ${rawText.slice(0, 200)}`);
    }

    let data;
    try {
      data = JSON.parse(rawText);
    } catch (err) {
      // Fallback ① try to grab a JSON-looking block
      const match = rawText.match(/\{[\s\S]*\}/);
      if (match) {
        try {
          data = JSON.parse(match[0]);
        } catch {
          data = { reflection_raw: rawText.trim(), notes: "partial parse" };
        }
      } else {
        // Fallback ② if it’s already an object (stringified Python dict)
        try {
          const normalized = rawText
            .replace(/'/g, '"')        // convert single quotes
            .replace(/None/g, 'null'); // convert Python None
          data = JSON.parse(normalized);
        } catch {
          data = { reflection_raw: rawText.trim(), notes: "no JSON found" };
        }
      }
    }

    if (typeof data !== "object") {
      data = { reflection_raw: rawText.trim(), notes: "non-object response" };
    }

    console.log("🧠 Cortex reflection normalized:", data);
    return data;
  } catch (e) {
    console.warn("⚠️ Cortex reflect failed:", e.message);
    return { error: e.message, reflection_raw: "" };
  }
}

export async function ingestToCortex(user, assistant, reflection = {}, sessionId = "default") {
  const body = { turn: { user, assistant }, reflection, session_id: sessionId };
  try {
    const res = await fetch(INGEST_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
      timeout: 120000,
    });
    console.log(`📤 Sent exchange to Cortex ingest (${res.status})`);
  } catch (e) {
    console.warn("⚠️ Cortex ingest failed:", e.message);
  }
}
