import axios from 'axios';

const API_BASE = "http://127.0.0.1:3001";

async function testMcp() {
    console.log("=== TelosDB MCP Tool Test ===");

    const messageEndpoint = "/messages";

    const postMessage = async (method, params = {}) => {
        try {
            const res = await axios.post(`${API_BASE}${messageEndpoint}`, {
                jsonrpc: "2.0",
                method: method,
                params: params,
                id: Date.now()
            });
            return res.data;
        } catch (e) {
            console.error(`  Error in ${method}:`, e.response?.data || e.message);
            throw e;
        }
    };

    try {
        // 1. ツール一覧
        console.log("\n[1] Listing tools...");
        const toolsResult = await postMessage("tools/list");
        console.log("  Success: Found", toolsResult.result?.tools?.length, "tools.");

        // 2. 登録 (スキップ)
        // console.log("\n[2] Testing add_item_text...");
        /*
        const addResult = await postMessage("tools/call", {
            name: "add_item_text",
            arguments: {
                content: "富士山は日本一の山です。",
                path: "test/mountain.txt"
            }
        });
        const addText = addResult.result?.content?.[0]?.text || "No text in response";
        console.log("  Response:", addText);

        // IDを抽出 (例: "Successfully added item with ID: 5")
        const idMatch = addText.match(/ID: (\d+)/);
        const testId = idMatch ? parseInt(idMatch[1]) : null;

        if (testId) {
            console.log(`  Identified new Item ID: ${testId}`);
        } else {
            console.warn("  Could not identify Item ID. Skipping Update/Delete tests.");
            console.log("  Raw add result:", JSON.stringify(addResult, null, 2));
        }
        */

        // 3. 検索テスト
        console.log("\n[3] Testing search_text with different queries...");

        const queries = ["宝くじ"];

        for (const q of queries) {
            console.log(`\n  Query: "${q}"`);
            const searchResult = await postMessage("tools/call", {
                name: "search_text",
                arguments: {
                    content: q,
                    limit: 5
                }
            });
            const content = searchResult.result?.content?.[0]?.text;
            console.log("  Result:\n", content || "  No results");
        }

    } catch (e) {
        console.error("\nTest failed.");
    } finally {
        console.log("\n=== Test Finished ===");
    }
}

testMcp();
