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

const __dirname = path.dirname(fileURLToPath(import.meta.url));
dotenv.config({ path: path.resolve(__dirname, "../.env") });

/**
 * EXPERT REVIEWER AGENT (Realistic Unified Example)
 * 
 * This example demonstrates the orchestration of all 3 MCP capability types:
 * 1. PROMPTS: Applying a standardized 'Code Review' template from the server.
 * 2. RESOURCES: Attaching specific repository files as context.
 * 3. TOOLS: Executing 'create_issue' or 'add_comment' to persist findings.
 */
async function run() {
  console.log("--- Starting Unified NodeLLM MCP Agent (Expert Reviewer) ---");

  // 1. Initialize Connection (Security/Auth at Transport Layer)
  const mcp = await MCP.connect({
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-github"],
    env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_PERSONAL_ACCESS_TOKEN || "" }
  });

  // Setup Event Listeners
  mcp
    .onLog(({ level, message }) => console.log(`[SERVER_LOG][${level}] ${message}`))
    .onProgress(({ progress, total }) => console.log(`[PROGRESS] ${progress}/${total}`))
    .onError(err => console.error("[PROTOCOL_ERROR]", err));

  try {
    const llm = createLLM();
    const chat = llm.chat("gpt-4o");

    // 2. Discover ALL Capabilities (Handshake)
    // We namespace tools with 'gh_' to prevent local collisions
    const { tools, resources, prompts } = await mcp.discover({ prefix: "gh_" });

    console.log(`\nDiscovered: ${tools.length} Tools, ${resources.length} Resources, ${prompts.length} Prompts`);

    // 3. Resolve specific Intent and Context
    // We look for a prompt that sounds like a review and a resource for source code
    const reviewerPrompt = prompts.find(p => p.name.includes("review")) || prompts[0];
    const sourceResource = resources.find(r => r.name.includes("src")) || resources[0];

    if (!reviewerPrompt || !sourceResource) {
      console.warn("Could not find specific review prompt or source resource. Falling back to generic flow.");
      
      chat.withTools(tools);
      
      const res = await chat.ask("Look at the latest issues in facebook/react and summarize them.");
      console.log("\n--- Summary ---");
      console.log(res.content);
      return;
    }

    console.log(`\nExecuting Workflow: Using Prompt [${reviewerPrompt.name}] on Resource [${sourceResource.uri}]`);

    // 4. Orchestrate (Unified Chain)
    // We read the resource content and apply it to the prompt template
    const sourceContent = await sourceResource.readText();
    const { messages } = await reviewerPrompt.get({ code: sourceContent });

    // 5. Run the session
    const response = await chat
      .withTools(tools)
      .addMessages(messages) // Using the new .addMessages() API
      .ask("Analyze this code and create a new GitHub issue for any security concerns found.");

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

  } finally {
    await mcp.close();
    console.log("\n--- Connection Closed ---");
  }
}

run().catch(console.error);
