
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import dotenv from "dotenv";
import path from "path";
import { fileURLToPath } from "url";

// Load environment variables
function loadEnv() {
    const __dirname = path.dirname(fileURLToPath(import.meta.url));
    const envPath = path.resolve(__dirname, "../../.env");
    const result = dotenv.config({ path: envPath });
    if (result.error) {
        console.warn(`Warning: .env file not found at ${envPath}`);
    }
    return process.env;
}

async function main() {
    console.log("=== Test Jira Myself & Search ===");

    const envVars = loadEnv();
    const serverPath = "/home/lethdat/projects/awing/mcp-jira-server/dist/index.js";

    const client = new Client({ name: "test-client-myself", version: "1.0.0" }, {
        capabilities: { promts: {}, resources: {}, tools: {} }
    });

    const transport = new StdioClientTransport({
        command: "node",
        args: [serverPath],
        env: { ...process.env, ...envVars }
    });

    await client.connect(transport);
    console.log("Connected to MCP server");

    try {
        // 1. Test jira://myself
        console.log(`\nTesting resource jira://myself...`);
        const myselfRes = await client.readResource({ uri: `jira://myself` });
        const myselfData = JSON.parse(String(myselfRes.contents[0].text));
        const user = myselfData.user?.[0] || myselfData; // Assuming standard resource format wrap in array under key 'user' or just data
        console.log(`Current User: ${user.displayName} (${user.emailAddress})`);

        // 2. Test searchIssues tool with currentUser()
        console.log(`\nTesting tool searchIssues with currentUser()...`);
        const jql = "assignee = currentUser() ORDER BY updated DESC";
        const searchResult = await client.callTool({
            name: "searchIssues",
            arguments: {
                jql: jql,
                maxResults: 5
            }
        });

        let searchData: any;
        if (searchResult.content && searchResult.content[0].text) {
            searchData = JSON.parse(searchResult.content[0].text);
        }

        console.log(`Found ${searchData.total} issues assigned to currentUser.`);
        if (searchData.issues && searchData.issues.length > 0) {
            console.log(`First issue: ${searchData.issues[0].key} - ${searchData.issues[0].summary}`);
        } else {
            console.log("No issues found for current user (possibly expected).");
        }

    } catch (error) {
        console.error(`Error testing:`, error);
    }

    client.close();
}

main().catch(console.error);
