import { createLLM } from "@node-llm/core";
import { MCP } from "../../packages/mcp/src/index.js";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.resolve(__dirname, "../../");

/**
 * KNOWLEDGE BASE AGENT (No Keys Required)
 * 
 * Demonstrates Tools, Resources, and Prompts using the local filesystem MCP server.
 * This is 100% runnable without any API keys.
 */
async function run() {
  console.log("--- Starting Filesystem Knowledge Agent ---");

  // 1. Connect to Local Filesystem MCP
  const mcp = await MCP.connect({
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-filesystem", projectRoot]
  });

  try {
    const llm = createLLM();
    const chat = llm.chat("gpt-4o-mini"); // Or any local provider

    // 2. Discover Capabilities
    const { tools, resources, prompts } = await mcp.discover({ prefix: "fs_" });
    console.log(`Discovered ${tools.length} Tools and ${resources.length} Resources.`);

    // 3. Realistic Resource Discovery
    // We look for the main documentation or README
    const readme = resources.find(r => r.name.toLowerCase().includes("readme"));
    
    if (readme) {
      console.log(`\nAnalyzing Resource: ${readme.uri}`);
      const content = await readme.readText();
      
      // Feed the resource into the conversation turn
      chat.add("user", `Here is the project README context: \n\n${content}`);
    }

    // 4. Expert Orchestration
    // We use the discovered tools to perform a deep analysis
    const response = await chat
      .withTools(tools)
      .ask("Analyze the project structure and create a 'ROADMAP.md' file if it doesn't exist, detailing the current MCP progress.");

    console.log("\n--- Agent Conclusion ---");
    console.log(response.content);

  } finally {
    await mcp.close();
  }
}

run().catch(console.error);
