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

const LOG_DIR = ".capint/logs";
const LOG_FILE = "route-events.ndjson";

function eventLogEnabled(rootDir) {
  if (process.env.CAPINT_EVENT_LOG === "1") return true;
  const ctxPath = path.join(rootDir, ".capint", "context.json");
  if (!fs.existsSync(ctxPath)) return false;
  try {
    const ctx = JSON.parse(fs.readFileSync(ctxPath, "utf-8"));
    return Boolean(ctx.event_log);
  } catch {
    return false;
  }
}

function appendRouteEvents(rootDir, events) {
  if (!rootDir || !Array.isArray(events) || events.length === 0) return { written: false };
  if (!eventLogEnabled(rootDir)) return { written: false, reason: "disabled" };

  const dir = path.join(rootDir, LOG_DIR);
  const file = path.join(dir, LOG_FILE);
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });

  const ts = new Date().toISOString();
  const lines = events.map((e) =>
    JSON.stringify({
      event_id: crypto.randomUUID(),
      ts,
      ...e
    })
  );
  fs.appendFileSync(file, `${lines.join("\n")}\n`, "utf-8");
  return { written: true, path: path.join(LOG_DIR, LOG_FILE), count: events.length };
}

module.exports = { appendRouteEvents, eventLogEnabled, LOG_DIR, LOG_FILE };
