// Tests for Anrubic MCP Tools functionality
import { spawn } from "child_process";
import path from "path";
import { fileURLToPath } from "url";
import { testToolCalls } from "./setup.ts";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Simple test function since we're having module issues
async function testMCPTools() {
  console.log("🔧 Testing Anrubic MCP Tools...\n");

  const tests = [
    {
      name: "Search for Lasher unit",
      request: {
        jsonrpc: "2.0",
        id: 1,
        method: "tools/call",
        params: testToolCalls.search_entities,
      },
    },
    {
      name: "Get all tags",
      request: {
        jsonrpc: "2.0",
        id: 2,
        method: "tools/call",
        params: testToolCalls.get_tags,
      },
    },
    {
      name: "Find attackers by tag",
      request: {
        jsonrpc: "2.0",
        id: 3,
        method: "tools/call",
        params: testToolCalls.find_by_tags,
      },
    },
    {
      name: "Get Griffin by ID",
      request: {
        jsonrpc: "2.0",
        id: 4,
        method: "tools/call",
        params: testToolCalls.fetch_entity_by_id,
      },
    },
    {
      name: "Get Grell faction data",
      request: {
        jsonrpc: "2.0",
        id: 5,
        method: "tools/call",
        params: testToolCalls.get_faction_data,
      },
    },
  ];

  for (const test of tests) {
    try {
      console.log(`Testing: ${test.name}...`);
      const result = await runMCPTest(test.request);

      if (result.error) {
        console.log(`❌ FAILED: ${test.name}`);
        console.log(`   Error: ${result.error.message}`);
      } else {
        console.log(`✅ PASSED: ${test.name}`);
        // Optionally log some result details
        if (test.name.includes("Lasher")) {
          const content = JSON.parse(result.result.content[0].text);
          console.log(`   Found: ${content.results[0]?.name || "No results"}`);
        }
        if (test.name.includes("Find attackers")) {
          const content = JSON.parse(result.result.content[0].text);
          console.log(`   Found ${content.totalMatches} attackers`);
        }
      }
    } catch (error) {
      console.log(`❌ ERROR: ${test.name}`);
      console.log(`   ${error}`);
    }

    console.log(); // Empty line for readability
  }
}

function runMCPTest(request: any): Promise<any> {
  return new Promise((resolve, reject) => {
    const serverPath = path.join(__dirname, "../dist/index.js");
    const process = spawn("node", [serverPath], {
      stdio: ["pipe", "pipe", "pipe"],
    });

    let output = "";
    let timeoutId: any;

    const cleanup = () => {
      if (timeoutId) clearTimeout(timeoutId);
      process.kill();
    };

    // 15 second timeout
    timeoutId = setTimeout(() => {
      cleanup();
      reject(new Error("Request timed out"));
    }, 15000);

    process.stdout.on("data", (data) => {
      output += data.toString();

      // Look for JSON-RPC response
      const lines = output.split("\n");
      for (const line of lines) {
        const trimmed = line.trim();
        if (
          trimmed.startsWith("{") &&
          trimmed.includes('"jsonrpc"') &&
          trimmed.includes('"id"')
        ) {
          try {
            const response = JSON.parse(trimmed);
            if (response.id === request.id) {
              cleanup();
              resolve(response);
              return;
            }
          } catch (e) {
            // Not valid JSON yet, continue
          }
        }
      }
    });

    process.stderr.on("data", (data) => {
      // Server startup logs go to stderr, ignore them
    });

    process.on("error", (error) => {
      cleanup();
      reject(error);
    });

    // Send the request
    process.stdin.write(JSON.stringify(request) + "\n");
    process.stdin.end();
  });
}

// Run the tests
testMCPTools().catch(console.error);
