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

export interface ToolJsonSchema {
  type: 'function';
  function: {
    name: string;
    description: string;
    parameters: Record<string, unknown>;
  };
}

// v2.6.x: optional DB/session context threaded into a tool's execute(). Only
// tools that need to read session-scoped DB state (e.g. read_tab_by_number)
// use it; every other tool ignores the 4th arg. Kept optional so existing
// 3-arg execute() implementations stay assignable (apps/coder consumes this
// type from the compiled dist — the optional param keeps it backward-compatible).
export interface ToolExecCtx {
  sql: Sql;
  sessionId: string;
  toolCallId?: string;
}

export interface ToolDef<TInput> {
  name: string;
  description: string;
  inputSchema: z.ZodType<TInput>;
  jsonSchema: ToolJsonSchema;
  // v1.13.17-cross-repo-reads: extraRoots is the session's
  // allowed_read_paths, threaded through executeToolCall in tool-phase.ts.
  // Only the filesystem tools (view_file, list_dir, grep, find_files,
  // view_truncated_output) forward it to pathGuard; other tools accept the
  // arg and ignore it. The execute signature stays compatible with
  // pre-v1.13.17 callsites because the parameter is optional.
  // v2.6.x: optional 4th param toolCtx carries DB/session context for tools
  // that read session-scoped state (read_tab_by_number). Optional so 3-arg
  // implementations remain assignable.
  execute(
    input: TInput,
    projectRoot: string,
    extraRoots?: readonly string[],
    toolCtx?: ToolExecCtx,
  ): Promise<unknown>;
}
