import type { Tool, ToolResult } from '../types.js';
import type { MemoryStore } from '../../memory/store.js';

interface MemoryWriteArgs {
  namespace: string;
  content: string;
  mode: 'append' | 'replace';
}

/**
 * Creates a memory.write tool bound to the given MemoryStore instance.
 * Writes or appends content to a persistent memory namespace.
 */
export function createMemoryWriteTool(store: MemoryStore): Tool {
  return {
    name: 'memory.write',
    description:
      'Write to a persistent memory file. Use mode="append" to add new information without overwriting existing content, or mode="replace" to overwrite the entire namespace. Supports structured category namespaces like "user/facts", "user/preferences", "user/decisions", and "user/projects".',
    inputSchema: {
      type: 'object',
      properties: {
        namespace: {
          type: 'string',
          description: 'Memory namespace to write to (e.g. "user", "global", "sessions/abc123")',
        },
        content: {
          type: 'string',
          description: 'The content to write',
        },
        mode: {
          type: 'string',
          enum: ['append', 'replace'],
          description: 'Write mode: "append" to add to existing content, "replace" to overwrite',
        },
      },
      required: ['namespace', 'content', 'mode'],
    },
    execute: async (rawArgs: unknown): Promise<ToolResult> => {
      const args = rawArgs as MemoryWriteArgs;

      try {
        store.write(args.namespace, args.content, args.mode);

        const verb = args.mode === 'append' ? 'Appended to' : 'Replaced';
        return {
          success: true,
          output: `${verb} namespace "${args.namespace}" successfully.`,
        };
      } catch (error) {
        return {
          success: false,
          output: '',
          error: error instanceof Error ? error.message : String(error),
        };
      }
    },
  };
}
