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

const FINANCE_SVC = process.env.FINANCE_SVC_URL?.trim() ?? 'http://localhost:3003';

const quoteSchema = z.object({
  ticker: z.string().describe('Stock ticker symbol (e.g. AAPL, TSLA)'),
});

export const quoteTool: ToolDef = {
  name: 'get_stock_quote',
  description: 'Get current stock price and quote data for a ticker symbol.',
  schema: quoteSchema,
  execute: async (params, _ctx) => {
    const { ticker } = quoteSchema.parse(params);
    const url = `${FINANCE_SVC.replace(/\/$/, '')}/api/v1/finance/quote/${encodeURIComponent(ticker)}`;
    try {
      const res = await fetch(url, { signal: AbortSignal.timeout(10000) });
      if (!res.ok) return JSON.stringify({ error: `HTTP ${res.status}` });
      const data = await res.json();
      return JSON.stringify(data, null, 2);
    } catch (err) {
      return JSON.stringify({ error: err instanceof Error ? err.message : 'Finance service unavailable' });
    }
  },
};
