import z from 'zod';
import { evaluate } from 'mathjs';
import type { ToolDef } from './types.js';

const schema = z.object({
  expression: z.string().describe('Math expression to evaluate, e.g. "2+3*4", "sqrt(16)"'),
});

export const calculatorTool: ToolDef = {
  name: 'calculator',
  description: 'Evaluate a mathematical expression. Use for arithmetic, percentages, unit conversions.',
  schema,
  execute: async (params, _ctx) => {
    const { expression } = schema.parse(params);
    try {
      const result = evaluate(expression);
      return JSON.stringify({ expression, result: String(result) });
    } catch (err) {
      return JSON.stringify({ error: err instanceof Error ? err.message : 'Invalid expression' });
    }
  },
};
