/**
 * Tracks Claude session IDs created by *the server itself* (scan-now,
 * per-thread checks). These chats land in ~/.claude/projects/ alongside
 * Pavel's real chats and would otherwise pollute the History panel.
 *
 * Capture pattern: every server-initiated `query()` listens for the
 * SDK's first `system/init` event and records its `session_id` here.
 * /api/chats then filters them out.
 *
 * Soft cap at 5000 ids (drop oldest). System chats never need more
 * than a few weeks of recall — they're noise to be hidden, not data.
 */
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { SYSTEM_SESSIONS_FILE } from "./paths";

const MAX_TRACKED = 5000;

let cache: Set<string> | null = null;

function load(): Set<string> {
  if (cache) return cache;
  if (!existsSync(SYSTEM_SESSIONS_FILE)) { cache = new Set(); return cache; }
  try {
    const data = JSON.parse(readFileSync(SYSTEM_SESSIONS_FILE, "utf8"));
    cache = new Set(Array.isArray(data) ? data : []);
  } catch {
    cache = new Set();
  }
  return cache;
}

function persist() {
  if (!cache) return;
  try {
    mkdirSync(dirname(SYSTEM_SESSIONS_FILE), { recursive: true });
    let arr = Array.from(cache);
    if (arr.length > MAX_TRACKED) {
      // FIFO: keep the most recent. JS Sets preserve insertion order.
      arr = arr.slice(arr.length - MAX_TRACKED);
      cache = new Set(arr);
    }
    writeFileSync(SYSTEM_SESSIONS_FILE, JSON.stringify(arr), "utf8");
  } catch (e) {
    console.error("[system-sessions] write failed:", e);
  }
}

export function addSystemSession(id: string): void {
  if (!id) return;
  const set = load();
  if (set.has(id)) return;
  set.add(id);
  persist();
}

export function isSystemSession(id: string): boolean {
  return load().has(id);
}

export function loadSystemSessions(): Set<string> {
  return load();
}
