// Profile timing helper. Toggle via sentinel file: touch ./tmp/profile.on
// Each event: appendFileSync to ./tmp/profile.log
// Format: <iso_ts> <label> <ms> [meta]
import { appendFileSync, existsSync } from "node:fs";
import { resolve } from "node:path";

const SENTINEL = resolve(process.cwd(), "tmp", "profile.on");
const LOG_PATH = resolve(process.cwd(), "tmp", "profile.log");

let lastCheck = 0;
let enabled = false;

function isEnabled(): boolean {
  const t = Date.now();
  if (t - lastCheck > 1000) {
    lastCheck = t;
    try { enabled = existsSync(SENTINEL); } catch { enabled = false; }
  }
  return enabled;
}

export function profileLog(label: string, durMs: number, meta?: string): void {
  if (!isEnabled()) return;
  try {
    const line = `${new Date().toISOString()} ${label} ${durMs.toFixed(2)}${meta ? " " + meta : ""}\n`;
    appendFileSync(LOG_PATH, line);
  } catch { /* swallow */ }
}

export function pnow(): number {
  return performance.now();
}
