import { DynamicStructuredTool } from '@langchain/core/tools';
import { z } from 'zod';
import type { FastifyBaseLogger } from 'fastify';
import type { WikiLoader } from '../../harness/spawn/wiki-loader.js';

export interface MemoryLookupToolConfig {
  wikiLoader: WikiLoader;
  logger: FastifyBaseLogger;
}

/**
 * Creates the `memory_lookup` tool for the main agent.
 *
 * Allows the agent to read a specific knowledge wiki page on demand,
 * or list available pages by passing "index".
 */
export function createMemoryLookupTool(config: MemoryLookupToolConfig): DynamicStructuredTool {
  const { wikiLoader, logger } = config;

  return new DynamicStructuredTool({
    name: 'MemoryLookup',
    description: `Read a knowledge wiki page by name to get detailed reference information.

Pass "index" to list all available pages.

Example pages:
- "api-reference" — DataAPI and ChartingAPI reference for research scripts
- "usage-examples" — Example research scripts
- "pandas-ta-reference" — Full pandas-ta indicator catalog`,
    schema: z.object({
      page: z.string().describe(
        'Wiki page name to read (without .md extension). Pass "index" to list all pages.'
      ),
    }),
    func: async ({ page }: { page: string }): Promise<string> => {
      logger.info({ page }, 'memory_lookup: reading page');

      if (page === 'index') {
        const pages = await wikiLoader.listPages();
        return `Available wiki pages:\n${pages.map(p => `- ${p}`).join('\n')}`;
      }

      const wikiPage = await wikiLoader.loadPage(page);
      if (!wikiPage) {
        const pages = await wikiLoader.listPages();
        return `Page "${page}" not found.\n\nAvailable pages:\n${pages.map(p => `- ${p}`).join('\n')}`;
      }

      return wikiPage.body;
    },
  });
}
