const fs = require("fs");
const path = require("path");

const LOCAL_SOURCES = [
  { path: "AGENT.md", confidence: "verbatim", role: "session_contract" },
  { path: "design.md", confidence: "verbatim", role: "project_boundaries" },
  { path: "HANDOFF.md", confidence: "verbatim", role: "session_history" },
  { path: ".capint/rules/core.md", confidence: "verbatim", role: "core_rules" }
];

function buildLocalContextPack({ rootDir, memoryLevel, providerActivated }) {
  if (memoryLevel === "none") {
    return { pack_id: null, snippets: [], truncated: false, source: "none" };
  }

  const snippets = [];
  for (const src of LOCAL_SOURCES) {
    const abs = path.join(rootDir, src.path);
    if (!fs.existsSync(abs)) continue;
    const text = fs.readFileSync(abs, "utf-8");
    const excerpt = text.slice(0, providerActivated ? 1200 : 600);
    snippets.push({
      text: excerpt,
      source: src.path,
      confidence: src.confidence,
      role: src.role
    });
  }

  return {
    pack_id: `local-${Date.now()}`,
    snippets,
    truncated: snippets.some((s) => s.text.length >= 600),
    source: providerActivated ? "local+provider_hint" : "local",
    token_budget_hint: providerActivated ? 2000 : 800
  };
}

module.exports = { buildLocalContextPack, LOCAL_SOURCES };
