/**
 * `budgetActiveBody` (token-diet, t_40eb1de7 part 2): fits the
 * rendered active.md body into the SessionStart injection budget,
 * dropping sections in fixed priority order (retired first, confirmed
 * last) and pointing the agent at `brain_context` when truncated.
 */

import { describe, expect, test } from "bun:test";

import { budgetActiveBody } from "../../../src/core/brain/active-budget.ts";

function body(): string {
  return [
    "# Active Brain Preferences",
    "",
    "Auto-generated by `dream`. Do not edit — changes will be overwritten.",
    "",
    "## Confirmed (2)",
    "",
    "- `pref-a` (confidence: high (0.95)) — Rule A",
    "- `pref-b` (confidence: medium (0.50)) — Rule B",
    "",
    "## Most-applied (30d) (1)",
    "",
    "- `pref-a` (applied_in_window: 4)",
    "",
    "## Quarantine (1)",
    "",
    "_Probationary rules — still active._",
    "",
    "- `pref-q` (applied: 0 / violated: 2) — Quarantined rule",
    "",
    "## Recently retired (last 1)",
    "",
    "- `pref-r` — low_confidence on 2026-05-01",
  ].join("\n");
}

describe("budgetActiveBody", () => {
  test("body within budget passes through byte-identical", () => {
    const input = body();
    const out = budgetActiveBody(input, 10_000);
    expect(out).toBe(input);
  });

  test("over budget: retired drops first, then quarantine, then most-applied", () => {
    const input = body();
    // Budget that can hold everything except the retired tail.
    const out = budgetActiveBody(input, input.length - 20);
    expect(out).toContain("## Confirmed");
    expect(out).not.toContain("## Recently retired");
    expect(out).toContain("brain_context");
  });

  test("tight budget keeps the confirmed head and points at brain_context", () => {
    const out = budgetActiveBody(body(), 250);
    expect(out).toContain("# Active Brain Preferences");
    expect(out).toContain("## Confirmed");
    expect(out).not.toContain("## Quarantine");
    expect(out).not.toContain("## Recently retired");
    expect(out).toContain("brain_context");
  });

  test("deterministic", () => {
    expect(budgetActiveBody(body(), 700)).toBe(budgetActiveBody(body(), 700));
  });

  test("unsectioned body still respects the budget", () => {
    const flat = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n");
    const out = budgetActiveBody(flat, 120);
    expect(out.length).toBeLessThanOrEqual(120 + 200); // content budget + notice overhead
    expect(out).toContain("line 0");
  });
});
