import { DynamicStructuredTool } from '@langchain/core/tools';
import { z } from 'zod';
import type { FastifyBaseLogger } from 'fastify';
import type { SymbolIndexService } from '../../services/symbol-index-service.js';

/**
 * Symbol Lookup Tool
 *
 * Standard LangChain tool for symbol search and resolution.
 * Supports two modes:
 * - search: Find symbols matching a query
 * - resolve: Get detailed metadata for a specific symbol
 */

export interface SymbolLookupToolConfig {
  symbolIndexService: SymbolIndexService;
  logger: FastifyBaseLogger;
}

export function createSymbolLookupTool(config: SymbolLookupToolConfig): DynamicStructuredTool {
  const { symbolIndexService, logger } = config;

  return new DynamicStructuredTool({
    name: 'SymbolLookup',
    description: `Search for market symbols or resolve symbol metadata. Use 'search' mode to find symbols matching a query, or 'resolve' mode to get detailed metadata for a specific symbol.

Parameters:
- mode (required): Either 'search' or 'resolve'
- query (required): Search query (for search mode) or symbol ticker (for resolve mode)
- limit (optional): Maximum number of search results (search mode only, default: 30)`,
    schema: z.object({
      mode: z.enum(['search', 'resolve']).describe('Operation mode: search for symbols or resolve a specific symbol'),
      query: z.string().describe('Search query (for search mode) or symbol ticker (for resolve mode)'),
      limit: z.number().optional().default(30).describe('Maximum number of search results (search mode only, default: 30)'),
    }),
    func: async ({ mode, query, limit }) => {
      logger.debug({ mode, query, limit }, 'Executing SymbolLookup tool');

      try {
        if (mode === 'search') {
          const results = await symbolIndexService.search(query, limit);

          logger.info({ query, resultCount: results.length }, 'Symbol search completed');

          return JSON.stringify({
            mode: 'search',
            query,
            count: results.length,
            results,
          });
        } else {
          const symbolInfo = await symbolIndexService.resolveSymbol(query);

          if (!symbolInfo) {
            logger.warn({ symbol: query }, 'Symbol not found');
            return JSON.stringify({
              error: `Symbol not found: ${query}`,
              symbol: query,
            });
          }

          logger.info({ symbol: query }, 'Symbol resolved');

          return JSON.stringify({
            mode: 'resolve',
            symbol: query,
            symbolInfo,
          });
        }
      } catch (error) {
        logger.error({ error, mode, query }, 'Symbol lookup tool failed');
        return JSON.stringify({
          error: error instanceof Error ? error.message : String(error),
        });
      }
    },
  });
}
