import { z } from 'zod';
import type { ToolDef, ToolContext } from './types.js';
import { resolveWritePath } from '../write_guard.js';
import { formatFileDiagnostics } from '../lsp/feedback.js';

const LspDiagnosticsInput = z.object({
  file_path: z.string().describe('Path to the file to check for diagnostics'),
});

type InputT = z.infer<typeof LspDiagnosticsInput>;

export const lspDiagnosticsTool: ToolDef<InputT> = {
  name: 'lsp_diagnostics',
  description: 'Get TypeScript/JavaScript diagnostics (errors, warnings) for a file. Returns diagnostic messages with severity and location.',
  inputSchema: LspDiagnosticsInput,
  jsonSchema: {
    type: 'function',
    function: {
      name: 'lsp_diagnostics',
      description: 'Get TypeScript/JavaScript diagnostics for a file',
      parameters: {
        type: 'object',
        properties: {
          file_path: { type: 'string', description: 'Path to the file' },
        },
        required: ['file_path'],
      },
    },
  },

  async execute(input: InputT, projectRoot: string, _context: ToolContext): Promise<unknown> {
    const resolved = resolveWritePath(projectRoot, input.file_path);
    const block = await formatFileDiagnostics(resolved);
    if (block === null) return { error: 'No diagnostics (unsupported file type or LSP unavailable).' };
    return { result: block };
  },
};
