import { createServer } from "../mcp/index.js";
import { config } from "dotenv";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
import yaml from "js-yaml";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { Logger } from "~/utils/logger.js";
import * as fs from 'fs';
config();

describe("Figma MCP Server Tests", () => {
  let server: McpServer;
  let client: Client;
  let figmaApiKey: string;
  let figmaFileKey: string;
  let nodeId: string;
  let isList: string;
  let isPage: string;

  beforeAll(async () => {
    figmaApiKey = process.env.FIGMA_API_KEY || "";
    if (!figmaApiKey) {
      throw new Error("FIGMA_API_KEY is not set in environment variables");
    }

    figmaFileKey = process.env.FIGMA_FILE_KEY || "";
    if (!figmaFileKey) {
      throw new Error("FIGMA_FILE_KEY is not set in environment variables");
    }

    nodeId = process.env.FIGMA_NODE_ID || "";
    if (!nodeId) {
      throw new Error("FIGMA_NODE_ID is not set in environment variables");
    }

    isList = process.env.FIGMA_NODE_LIST || "false"
    isPage = process.env.FIGMA_PAGE || "false";

    server = createServer({
      figmaApiKey,
      figmaOAuthToken: "",
      useOAuth: false,
    });

    client = new Client(
      {
        name: "figma-test-client",
        version: "1.0.0",
      },
      {
        capabilities: {
          tools: {},
        },
      },
    );

    const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();

    await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
  });

  afterAll(async () => {
    // await client.close();
  });

  describe("Get Figma Data", () => {
    it("should be able to get Figma file data", async () => {
      Logger.logA("isPage: "+isPage);
      if(isPage=="true"){
          const args: any = {
          fileKey: figmaFileKey,
          nodeId : nodeId
          };
          const result = await client.request(
            {
              method: "tools/call",
              params: {
                name: "get_figma_page",
                arguments: args,
              },
            },
            CallToolResultSchema,
          );
          const content = result.content[0].text as string;
          const parsed = yaml.load(content);
          expect(parsed).toBeDefined();
      }else{
          const args: any = {
          fileKey: figmaFileKey,
          nodeId : nodeId
          };
          const result = await client.request(
            {
              method: "tools/call",
              params: {
                name: "get_figma_data",
                arguments: args,
              },
            },
            CallToolResultSchema,
          );
          const content = result.content[0].text as string;
          const parsed = yaml.load(content);
          expect(parsed).toBeDefined();

        //暂时先自定义json集合，后续还是要以单链接自动拆分
        // if(isList == "true"){
        //   const data = readFigmaDataSync("nodes.json");
        //         const figmaUrls = Object.values(data).map(item => item.figma);
        //         figmaUrls.forEach(async (url, index) => {
        //             const nodeIdMatch = url.match(/node-id=([^&]+)/);
        //             if (nodeIdMatch) {
        //               console.log(`节点ID: ${nodeIdMatch[1]}`);
        //               const args: any = {
        //                 fileKey: figmaFileKey,
        //                 nodeId : nodeIdMatch[1]
        //               };
        //               const result = await client.request(
        //               {
        //                 method: "tools/call",
        //                 params: {
        //                   name: "get_figma_data",
        //                   arguments: args,
        //                 },
        //               },
        //               CallToolResultSchema,
        //             );

        //             }
        //           });
        // }
      }

     

    }, 60000);
  });
});
 

interface FigmaData {
  [key: string]: {
    figma: string;
  };
}

// 同步读取文件
function readFigmaDataSync(filePath: string): FigmaData {
  try {
    const fileContent = fs.readFileSync(filePath, 'utf-8');
    const data: FigmaData = JSON.parse(fileContent);
    return data;
  } catch (error) {
    console.error('读取文件失败:', error);
    throw error;
  }
}