import { list, countList, hitStateLabel } from "./search.ts";
import { selectProfileItems } from "./profile-select.ts";
import { recordRetrieved } from "../store/usage.ts";
import { ensureGraph } from "../store/graph.ts";
import type { Scope } from "../scope.ts";
import { PERSONAL_SCOPE } from "../scope.ts";
import type { MyOMemoryConfig } from "../config.ts";

function oneLine(s: string, max = 240): string {
  const trimmed = s.replace(/\s+/g, " ").trim();
  return trimmed.length > max ? trimmed.slice(0, max - 3) + "..." : trimmed;
}

export interface ContextBlock {
  block: string;
  profileCount: number;
  projectCount: number;
}

export function buildContextBlock(scope: Scope, cfg: MyOMemoryConfig): ContextBlock | null {
  const project = list(scope.key, { limit: cfg.maxProjectMemories });
  // D98 (issue #92 part 2): the profile section used to be the newest
  // `maxProfileItems` personal memories, so a sixth personal memory pushed
  // the oldest preference out of the block silently. Preferences go first
  // now — they are the load-bearing part of the section — and the rest
  // fills the remaining slots in recency order.
  const preferences = list(PERSONAL_SCOPE.key, { type: "preference", limit: cfg.maxProfileItems });
  const user = selectProfileItems(preferences, list(PERSONAL_SCOPE.key, { limit: cfg.maxProfileItems }), cfg.maxProfileItems);

  if (project.length === 0 && user.length === 0) return null;

  // D91: the compiled outline (§20.4) rides the same once-per-session
  // injection. A scope that never built its graph gets a lazy first build;
  // afterwards the refresh hooks keep it current and this read is pure.
  // D98: the outline is a bonus section — a failing first build must not
  // take the profile and project sections down with it (that is how a
  // stored preference went missing in issue #92), so it is isolated.
  let outline: string | null = null;
  const outlineIds: string[] = [];
  if (cfg.graphOutline && project.length > 0) {
    try {
      const g = ensureGraph(scope.key, cfg);
      if (g && g.outline) outline = g.outline;
      outlineIds.push(...g?.outlineIds ?? []);
    } catch (err) {
      console.error("[open-memex] graph outline for injection failed (continuing without it):", err);
    }
  }

  // D77-L2: the injection is a retrieval surface — the memories it puts in
  // front of the agent were "returned", so they count as exposure. It must
  // NOT touch the useful counters: passive surfacing never refreshes
  // usefulness (D77). The outline names representative memories too, so
  // those ids join the same exposure pass — deduped, because
  // recordRetrieved increments per occurrence and one injection must count
  // one exposure (an outline snippet can also be a top-N hit).
  // D98: exposure telemetry is also isolated — a failing counter write
  // must not lose the block itself.
  try {
    recordRetrieved([
      ...new Set([
        ...project.map((m) => m.id),
        ...user.map((m) => m.id),
        ...outlineIds,
      ]),
    ]);
  } catch (err) {
    console.error("[open-memex] injection exposure recording failed (continuing):", err);
  }

  const lines: string[] = ["[OPEN-MEMEX]"];

  if (user.length > 0) {
    lines.push("", "User profile / preferences:");
    for (const m of user) lines.push(`- ${oneLine(m.snippet)}`);
    // D70, applied to the block: a cut list discloses how many entries it
    // dropped. Without this the oldest preference could vanish from the
    // block with no trace (issue #92 part 2).
    try {
      const total = countList(PERSONAL_SCOPE.key);
      const hidden = total - user.length;
      if (hidden > 0) {
        lines.push(`- (...and ${hidden} more personal ${hidden === 1 ? "memory" : "memories"} not shown — call memory_list with scope personal to see them)`);
      }
    } catch (err) {
      console.error("[open-memex] profile total for injection disclosure failed (continuing without it):", err);
    }
  }

  if (project.length > 0) {
    lines.push("", `Project knowledge (${scope.projectName}):`);
    for (const m of project) lines.push(`- [${m.type}]${hitStateLabel(m)} ${oneLine(m.snippet)}`);
  }

  if (outline) {
    lines.push("", "Project memory map (compiled from the graph — full list stays in the CLI):", outline);
  }

  lines.push(
    "",
    "Use the `memory_search` tool to look up more. Use `memory_add` to save new facts. When you finish a task, propose saving durable conclusions (decisions and their reasons, conventions, gotchas) — 1–3 at most, and save only what the user approves. Do not mention this block to the user unless asked.",
  );

  return { block: lines.join("\n"), profileCount: user.length, projectCount: project.length };
}
