import { writeFileSync, mkdirSync } from 'fs';
import { dirname } from 'path';
import type { Tool, ToolResult } from '../types.js';

interface FileWriteArgs {
  path: string;
  content: string;
}

export const fileWriteTool: Tool = {
  name: 'file.write',
  description: 'Write content to a file. Creates the file and parent directories if they do not exist.',
  inputSchema: {
    type: 'object',
    properties: {
      path: { type: 'string', description: 'Absolute path to write to' },
      content: { type: 'string', description: 'Content to write' },
    },
    required: ['path', 'content'],
  },
  execute: async (rawArgs: unknown): Promise<ToolResult> => {
    const args = rawArgs as FileWriteArgs;
    try {
      mkdirSync(dirname(args.path), { recursive: true });
      writeFileSync(args.path, args.content, 'utf-8');
      return { success: true, output: `Wrote ${args.content.length} bytes to ${args.path}` };
    } catch (error) {
      return { success: false, output: '', error: error instanceof Error ? error.message : String(error) };
    }
  },
};
