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

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

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