import {
  DREAMING_SYSTEM_PROMPT,
  UPDATE_MEMORIES_TOOL
} from "./chunk-3LUY2POB.js";
import {
  createOrUpsertMemory,
  deleteMemory,
  getMemoryByPath,
  getMemoryStore,
  listMemories
} from "./chunk-2UKAINAN.js";
import {
  listSessions
} from "./chunk-SEGKFEG5.js";
import {
  listEvents
} from "./chunk-LH3NEWMT.js";
import {
  init_clock,
  nowMs
} from "./chunk-HFDLUBWN.js";

// src/dreaming/review.ts
init_clock();
var MAX_SESSIONS = 20;
var MAX_EVENTS_PER_SESSION = 50;
var RELEVANT_EVENT_TYPES = ["user.message", "agent.message", "session.error"];
function extractSessionSummary(sessionId, title, events) {
  const parts = [];
  const errors = [];
  for (const evt of events) {
    let payload;
    try {
      payload = JSON.parse(evt.payload_json);
    } catch {
      continue;
    }
    if (evt.type === "user.message") {
      const content = payload.content;
      if (Array.isArray(content)) {
        const text = content.filter((b) => b.type === "text").map((b) => b.text ?? "").join(" ");
        if (text) parts.push(`[User] ${text.slice(0, 500)}`);
      } else if (typeof content === "string") {
        parts.push(`[User] ${content.slice(0, 500)}`);
      }
    } else if (evt.type === "agent.message") {
      const content = payload.content;
      if (Array.isArray(content)) {
        const text = content.filter((b) => b.type === "text").map((b) => b.text ?? "").join(" ");
        if (text) parts.push(`[Agent] ${text.slice(0, 500)}`);
      } else if (typeof content === "string") {
        parts.push(`[Agent] ${content.slice(0, 500)}`);
      }
    } else if (evt.type === "session.error") {
      const msg = payload.message ?? payload.error ?? JSON.stringify(payload);
      errors.push(msg.slice(0, 200));
    }
  }
  const header = `Session ${sessionId}${title ? ` (${title})` : ""}:`;
  const body = parts.join("\n");
  const errorSection = errors.length ? `
Errors: ${errors.join("; ")}` : "";
  return `${header}
${body}${errorSection}`;
}
async function reviewSessions(opts) {
  const { storeId, lookbackMs, dryRun } = opts;
  const store = getMemoryStore(storeId);
  if (!store) {
    throw new Error(`Memory store not found: ${storeId}`);
  }
  const apiKey = opts.apiKey || process.env.ANTHROPIC_API_KEY;
  if (!apiKey) {
    throw new Error("No Anthropic API key provided. Use --api-key or set ANTHROPIC_API_KEY.");
  }
  const cutoff = nowMs() - lookbackMs;
  const sessions = listSessions({
    statuses: ["idle", "terminated"],
    createdGt: cutoff,
    limit: MAX_SESSIONS,
    order: "desc"
  });
  if (sessions.length === 0) {
    return { sessionCount: 0, proposedChanges: [], applied: false };
  }
  const summaries = [];
  for (const session of sessions) {
    const events = listEvents(session.id, {
      limit: MAX_EVENTS_PER_SESSION,
      order: "asc"
    });
    const relevant = events.filter((e) => RELEVANT_EVENT_TYPES.includes(e.type));
    if (relevant.length === 0) continue;
    const summary = extractSessionSummary(session.id, session.title ?? null, relevant);
    summaries.push(summary);
  }
  if (summaries.length === 0) {
    return { sessionCount: sessions.length, proposedChanges: [], applied: false };
  }
  const memories = listMemories(storeId);
  const memorySection = memories.length > 0 ? `## Current Memory Store Contents

${memories.map((m) => `### ${m.path}
${m.content}`).join("\n\n")}` : "## Current Memory Store Contents\n\n(empty \u2014 no memories yet)";
  const sessionSection = `## Recent Sessions (${summaries.length})

${summaries.join("\n\n---\n\n")}`;
  const userMessage = `${sessionSection}

${memorySection}

Analyze the sessions above and propose memory changes using the update_memories tool.`;
  const maxChars = 2e5;
  const truncatedMessage = userMessage.length > maxChars ? userMessage.slice(0, maxChars) + "\n\n[... truncated for context limits]" : userMessage;
  const response = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-api-key": apiKey,
      "anthropic-version": "2023-06-01"
    },
    body: JSON.stringify({
      model: opts.model || "claude-sonnet-4-6",
      max_tokens: 4096,
      system: DREAMING_SYSTEM_PROMPT,
      tools: [UPDATE_MEMORIES_TOOL],
      tool_choice: { type: "tool", name: "update_memories" },
      messages: [{ role: "user", content: truncatedMessage }]
    })
  });
  if (!response.ok) {
    const errText = await response.text().catch(() => "");
    throw new Error(`Anthropic API error (${response.status}): ${errText}`);
  }
  const data = await response.json();
  const toolUse = data.content.find(
    (b) => b.type === "tool_use" && b.name === "update_memories"
  );
  const changes = toolUse?.input?.changes ?? [];
  if (!dryRun && changes.length > 0) {
    for (const change of changes) {
      if (change.operation === "create" || change.operation === "update") {
        if (change.content) {
          createOrUpsertMemory(storeId, change.path, change.content, "dream");
        }
      } else if (change.operation === "delete") {
        const existing = getMemoryByPath(storeId, change.path);
        if (existing) {
          deleteMemory(existing.id, "dream");
        }
      }
    }
  }
  return {
    sessionCount: sessions.length,
    proposedChanges: changes,
    applied: !dryRun && changes.length > 0
  };
}

export {
  extractSessionSummary,
  reviewSessions
};
