import type { Sql } from '../../db.js';

/**
 * Module-level inference context for write tools.
 *
 * Set via `setInferenceContext()` before each inference run starts.
 * Write tools read it via `getInferenceContext()` during execute.
 * Same pattern as BooChat's `loadConfig()` singleton — tools need
 * ambient state that can't be threaded through the tool-phase execute
 * signature (which is `execute(input, projectRoot, extraRoots?)`).
 */

export interface InferenceContext {
  sql: Sql;
  sessionId: string;
  taskId: string | null;
}

let current: InferenceContext | null = null;

export function setInferenceContext(ctx: InferenceContext): void {
  current = ctx;
}

export function clearInferenceContext(): void {
  current = null;
}

export function getInferenceContext(): InferenceContext {
  if (!current) {
    throw new Error(
      'Write tool called outside inference context — setInferenceContext() was not called before this run',
    );
  }
  return current;
}
