import { z } from 'zod';
import type { ToolDef, ToolContext } from './types.js';
import { queueDelete } from '../pending_changes.js';
import { denyReadOnly, finalizeWrite } from './write-gate.js';

const DeleteFileInput = z.object({
  file_path: z.string().min(1),
});
type DeleteFileInputT = z.infer<typeof DeleteFileInput>;

export const deleteFileTool: ToolDef<DeleteFileInputT> = {
  name: 'delete_file',
  description:
    'Queue deletion of a file. ' +
    'The change is staged in pending_changes and must be applied explicitly.',
  inputSchema: DeleteFileInput,
  jsonSchema: {
    type: 'function',
    function: {
      name: 'delete_file',
      description:
        'Queue deletion of a file. ' +
        'The change is staged in pending_changes and must be applied explicitly.',
      parameters: {
        type: 'object',
        properties: {
          file_path: { type: 'string', description: 'Path to the file to delete (relative to project root or absolute)' },
        },
        required: ['file_path'],
      },
    },
  },
  async execute(input: DeleteFileInputT, projectRoot: string, context: ToolContext): Promise<unknown> {
    if (context.permissionMode === 'plan') return denyReadOnly('delete_file');
    const change = await queueDelete(
      context.sql,
      context.sessionId,
      context.taskId,
      input.file_path,
      projectRoot,
    );
    return finalizeWrite(
      context,
      projectRoot,
      change,
      `File deletion queued: ${change.file_path}. Use apply_pending to write changes to disk.`,
    );
  },
};
