/**
 * Write tool — create or overwrite files in the workspace.
 */

import { writeFileSync, mkdirSync, existsSync } from 'fs';
import { resolve, normalize, dirname } from 'path';

export const definition = {
  name: 'Write',
  description: 'Write content to a file, creating parent directories if needed. Overwrites if the file exists. You must Read existing files before writing.',
  input_schema: {
    type: 'object',
    properties: {
      file_path: { type: 'string', description: 'Absolute path to the file to write' },
      content: { type: 'string', description: 'Content to write to the file' }
    },
    required: ['file_path', 'content']
  }
};

export async function execute(input, context) {
  const { file_path, content } = input;

  if (!file_path) return { content: 'Error: file_path is required', is_error: true };
  if (content === undefined || content === null) return { content: 'Error: content is required', is_error: true };

  const resolved = resolve(normalize(file_path));
  const wsNorm = resolve(normalize(context.workspaceRoot));

  // Write only within workspace
  if (!resolved.startsWith(wsNorm)) {
    return { content: `Error: Write is restricted to workspace: ${context.workspaceRoot}`, is_error: true };
  }

  // Safety: warn if file exists but wasn't Read first
  if (existsSync(resolved) && context.readFileTimestamps && !context.readFileTimestamps[resolved]) {
    return {
      content: `Error: File "${resolved}" exists but has not been Read in this session. Read it first to confirm you want to overwrite.`,
      is_error: true
    };
  }

  try {
    mkdirSync(dirname(resolved), { recursive: true });
    writeFileSync(resolved, content, 'utf-8');
    const bytes = Buffer.byteLength(content, 'utf-8');
    return { content: `Wrote ${bytes} bytes to ${resolved}`, is_error: false };
  } catch (err) {
    return { content: `Error writing file: ${err.message}`, is_error: true };
  }
}
