import { z } from "zod";
import type { GetFileResponse, GetFileNodesResponse,Component,ComponentSet,Style } from "@figma/rest-api-spec";
import { FigmaService } from "~/services/figma.js";
// 使用示例
import { convertFigmaToDSL, parseFigmaJSON } from './get-figma-to-dsl.js';
import {
  simplifyRawFigmaObject,
  allExtractors,
  parseAPIResponse,
  collapseSvgContainers,
} from "~/extractors/index.js";
import yaml from "js-yaml";
import { Logger, writeLogs } from "~/utils/logger.js";
import {DSLCollection} from "~/utils/dsl-page-colletion.js"

const parameters = {
  fileKey: z
    .string()
    .regex(/^[a-zA-Z0-9]+$/, "File key must be alphanumeric")
    .describe(
      "The key of the Figma file to fetch, often found in a provided URL like figma.com/(file|design)/<fileKey>/...",
    ),
  nodeId: z
    .string()
    .regex(
      /^I?\d+[:|-]\d+(?:;\d+[:|-]\d+)*$/,
      "Node ID must be like '1234:5678' or 'I5666:180910;1:10515;1:10336'",
    )
    .optional()
    .describe(
      "The ID of the node to fetch, often found as URL parameter node-id=<nodeId>, always use if provided. Use format '1234:5678' or 'I5666:180910;1:10515;1:10336' for multiple nodes.",
    ),
  depth: z
    .number()
    .optional()
    .describe(
      "OPTIONAL. Do NOT use unless explicitly requested by the user. Controls how many levels deep to traverse the node tree.",
    ),
};

const parametersSchema = z.object(parameters);
export type GetFigmaDataParams = z.infer<typeof parametersSchema>;

// Simplified handler function
async function getFigmaData(
  params: GetFigmaDataParams,
  figmaService: FigmaService,
  outputFormat: "yaml" | "json",
) {
  try {
    const { fileKey, nodeId: rawNodeId, depth } = parametersSchema.parse(params);

    // Replace - with : in nodeId for our query—Figma API expects :
    const nodeId = rawNodeId?.replace(/-/g, ":");

    Logger.log(
      `Fetching ${depth ? `${depth} layers deep` : "all layers"} of ${
        nodeId ? `node ${nodeId} from file` : `full file`
      } ${fileKey}`,
    );

    // Get raw Figma API response
    let startTime = Date.now()
    let rawApiResponse: GetFileResponse | GetFileNodesResponse;
    if (nodeId) {
      rawApiResponse = await figmaService.getRawNode(fileKey, nodeId, depth);
    } else {
      rawApiResponse = await figmaService.getRawFile(fileKey, depth);
    }
    const apiCost = Date.now()-startTime
    startTime = Date.now();
    const baseUrl = "https://www.figma.com";
    const endpoint = `/file/${fileKey}/image/`;
    const fileUrl = (baseUrl+endpoint);

    writeLogs("figma-rawApiResponse"+nodeId?.replace(":", "_")+".json", rawApiResponse);
    
    // Use unified design extraction (handles nodes + components consistently)
    const simplifiedDesign = simplifyRawFigmaObject(fileUrl,rawApiResponse, allExtractors, {
      maxDepth: depth,
      afterChildren: collapseSvgContainers,
    });
    const convertFigmaCost = Date.now()-startTime;
    startTime = Date.now();
   
    writeLogs("figma-simplified"+nodeId?.replace(":", "_")+".json", simplifiedDesign);
  
    // 解析Figma JSON
    const figmaData = parseFigmaJSON(JSON.stringify(simplifiedDesign, null, 2));
    // 转换为DSL
    let formattedResult;
    if(figmaData.nodes && figmaData.nodes.length>0){
      const dslResult = convertFigmaToDSL(figmaData.nodes, figmaData.globalStyles);
      formattedResult = JSON.stringify(dslResult, null, 2);
    }else{
      formattedResult = "{}";
    }
    const convertDslCost = Date.now()-startTime; 
    // Logger.logB("cost: apiCost:"+apiCost+" , convertFigmaCost:"+convertFigmaCost+" , convertDslCost："+convertDslCost)
    // writeLogs("figma-dsl-"+nodeId?.replace(":", "_")+".json", dslResult);
    // Logger.log(
    //   `Successfully extracted data: ${simplifiedDesign.nodes.length} nodes, ${
    //     Object.keys(simplifiedDesign.globalVars.styles).length
    //   } styles`,
    // );
    // const { nodes, globalVars, ...metadata } = simplifiedDesign;
    // const result = {
    //   metadata,
    //   nodes,
    //   globalVars,
    // };

    // Logger.log(`Generating ${outputFormat.toUpperCase()} result from extracted data`);
    
      // outputFormat === "json" ? JSON.stringify(result, null, 2) : yaml.dump(result);

    // Logger.log("Sending result to client : "+formattedResult);
    writeLogs("formattedResult.json", formattedResult);
    
    return {
      content: [{ type: "text" as const,  text: formattedResult }],
    };
  } catch (error) {
    const message = error instanceof Error ? error.message : JSON.stringify(error);
    Logger.error(`Error fetching file ${params.fileKey}:`, message);
    return {
      isError: true,
      content: [{ type: "text" as const, text: `Error fetching file: ${message}` }],
    };
  }
}

// Export tool configuration
export const getFigmaDataTool = {
  name: "get_figma_data",
  description:
    "Get comprehensive Figma file data including layout, content, visuals, and component information",
  parameters,
  handler: getFigmaData,
} as const;




// Simplified handler function
async function getFigmaPage(
  params: GetFigmaDataParams,
  figmaService: FigmaService,
  outputFormat: "yaml" | "json",
) {
  try {
    const { fileKey, nodeId: rawNodeId, depth } = parametersSchema.parse(params);
    // Replace - with : in nodeId for our query—Figma API expects :
    const nodeId = rawNodeId?.replace(/-/g, ":");
    Logger.log(
      `Fetching ${depth ? `${depth} layers deep page` : "all layers page"} of ${
        nodeId ? `node ${nodeId} from file` : `full file`
      } ${fileKey}`,
    );
    // Get raw Figma API response
    let pageApiResponse: GetFileResponse | GetFileNodesResponse;
    if (nodeId) {
      pageApiResponse = await figmaService.getRawNode(fileKey, nodeId, depth);
       const { metadata, rawNodes, components, componentSets, extraStyles } = parseAPIResponse(pageApiResponse);
       const pageRootNodes  = rawNodes[0]
       const baseUrl = "https://www.figma.com";
       const endpoint = `/file/${fileKey}/image/`;
       const fileUrl = (baseUrl+endpoint);
       let contentJSON   ;
       if("children" in pageRootNodes){
          const collection = new DSLCollection();
           const pageChildNodes = Object.values(pageRootNodes.children);
          pageChildNodes.forEach((pageChildNode) => {
            const nodes_ = {
                [pageChildNode.id]: {
                  document: pageChildNode,
                  components: {}, // 根据实际情况填充或留空对象
                  componentSets: {}, // 根据实际情况填充或留空对象
                  schemaVersion: 0, // 设置正确的 schema 版本号
                  styles: {} // 根据实际情况填充或留空对象
                }
              };
             const pageChildConverNode: GetFileNodesResponse = {
            // 根据 GetFileResponse 的构造函数参数来映射字段
              nodes:nodes_,
              name: pageChildNode.name,
              lastModified:  new Date().toISOString(),
              thumbnailUrl: "",
              version: "2283563295863919804",
              role: "owner",
              editorType: "figma",
              // 其他需要的属性...
              // 根据你的实际需求添加更多字段映射
            };
            Logger.logA("------- "+pageChildNode+" , "+pageChildNode.id);
            const pageChildNodeSimplifiedDesign = simplifyRawFigmaObject(fileUrl,pageChildConverNode, allExtractors, {
              maxDepth: depth,
              // afterChildren: collapseSvgContainers,
            });
            writeLogs("page-simplified-"+pageChildNode.id.replace(":","-")+".json",pageChildNodeSimplifiedDesign);
             // 解析Figma JSON
           const figmaData = parseFigmaJSON(JSON.stringify(pageChildNodeSimplifiedDesign, null, 2));
            // 转换为DSL
           try{
                if(figmaData.nodes && figmaData.nodes.length>0){
                  const dslResult = convertFigmaToDSL(figmaData.nodes, figmaData.globalStyles);
                  if((dslResult.type == "column" || dslResult.type == "row") && !!dslResult.children && dslResult.children.length > 0){
                    writeLogs("dsl-"+pageChildNode.id.replace(":","-")+".json",dslResult);
                    collection.add(dslResult);
                    writeLogs("page-origin-"+pageChildNode.id.replace(":","-")+".json",pageChildConverNode);
                  }else{
                    Logger.error("dsl 为空");
                  }
                }
           } catch (error) {
              Logger.error(error);
              throw new Error('extractFillAttributes: ');
           }
           
          });
          contentJSON = JSON.stringify(collection.toJSON(), null, 2);
       }else{
          contentJSON = "[]";
       }
      // const formattedResult =
      //   outputFormat === "json" ? JSON.stringify(pageApiResponse, null, 2) : yaml.dump(pageApiResponse);
      // writeLogs("figma-page"+nodeId?.replace(":", "_")+".json", pageApiResponse);
      // return {
      //   content: [{ type: "text" as const, text: formattedResult }],
      // };
        // outputFormat === "json" ? JSON.stringify(result, null, 2) : yaml.dump(result);

        Logger.log("Sending result to client : "+contentJSON);
        writeLogs("formattedResult.json", contentJSON);
        
        return {
          content: [{ type: "text" as const,  text: contentJSON }],
        };

    }else{
      Logger.logA("nodeId is null: "+nodeId);
       return {
        content: [{ type: "text" as const, text: "" }],
      };
    }

  } catch (error) {
    const message = error instanceof Error ? error.message : JSON.stringify(error);
    Logger.error(`Error fetching file ${params.fileKey}:`, message);
    return {
      isError: true,
      content: [{ type: "text" as const, text: `Error fetching file: ${message}` }],
    };
  }
}



// Export tool configuration
export const getFigmaPageTool = {
  name: "get_figma_page",
  description:
    "Get comprehensive Figma file data including layout, content, visuals, and component information",
  parameters,
  handler: getFigmaPage,
} as const;