// src/utils/common.ts
import fs from "fs";
import path from "path";
async function downloadFigmaImage(fileName, localPath, imageUrl) {
  try {
    if (!fs.existsSync(localPath)) {
      fs.mkdirSync(localPath, { recursive: true });
    }
    const fullPath = path.join(localPath, fileName);
    const response = await fetch(imageUrl, {
      method: "GET"
    });
    if (!response.ok) {
      throw new Error(`Failed to download image: ${response.statusText}`);
    }
    const writer = fs.createWriteStream(fullPath);
    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error("Failed to get response body");
    }
    return new Promise((resolve, reject) => {
      const processStream = async () => {
        try {
          while (true) {
            const { done, value } = await reader.read();
            if (done) {
              writer.end();
              break;
            }
            writer.write(value);
          }
        } catch (err) {
          writer.end();
          fs.unlink(fullPath, () => {
          });
          reject(err);
        }
      };
      writer.on("finish", () => {
        resolve(fullPath);
      });
      writer.on("error", (err) => {
        reader.cancel();
        fs.unlink(fullPath, () => {
        });
        reject(new Error(`Failed to write image: ${err.message}`));
      });
      processStream();
    });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    throw new Error(`Error downloading image: ${errorMessage}`);
  }
}
function removeEmptyKeys(input) {
  if (typeof input !== "object" || input === null) {
    return input;
  }
  if (Array.isArray(input)) {
    return input.map((item) => removeEmptyKeys(item));
  }
  const result = {};
  for (const key in input) {
    if (Object.prototype.hasOwnProperty.call(input, key)) {
      const value = input[key];
      const cleanedValue = removeEmptyKeys(value);
      if (cleanedValue !== void 0 && !(Array.isArray(cleanedValue) && cleanedValue.length === 0) && !(typeof cleanedValue === "object" && cleanedValue !== null && Object.keys(cleanedValue).length === 0)) {
        result[key] = cleanedValue;
      }
    }
  }
  return result;
}
function generateVarId(prefix = "var") {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let result = "";
  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    result += chars[randomIndex];
  }
  return `${prefix}_${result}`;
}
function generateCSSShorthand(values, {
  ignoreZero = true,
  suffix = "px"
} = {}) {
  const { top, right, bottom, left } = values;
  if (ignoreZero && top === 0 && right === 0 && bottom === 0 && left === 0) {
    return void 0;
  }
  if (top === right && right === bottom && bottom === left) {
    return `${top}${suffix}`;
  }
  if (right === left) {
    if (top === bottom) {
      return `${top}${suffix} ${right}${suffix}`;
    }
    return `${top}${suffix} ${right}${suffix} ${bottom}${suffix}`;
  }
  return `${top}${suffix} ${right}${suffix} ${bottom}${suffix} ${left}${suffix}`;
}
function isVisible(element) {
  return element.visible ?? true;
}
function pixelRound(num) {
  if (isNaN(num)) {
    throw new TypeError(`Input must be a valid number`);
  }
  return Number(Number(num).toFixed(2));
}

export {
  downloadFigmaImage,
  removeEmptyKeys,
  generateVarId,
  generateCSSShorthand,
  isVisible,
  pixelRound
};
