import { writeFile } from "node:fs/promises";

const FILE_KEY = process.env.FIGMA_FILE_KEY;
const TOKEN = process.env.FIGMA_TOKEN;

if (!FILE_KEY || !TOKEN) {
  throw new Error("Set FIGMA_FILE_KEY and FIGMA_TOKEN in your .env file.");
}

const filePath = `/files/${encodeURIComponent(FILE_KEY)}`;

async function figma(path) {
  const response = await fetch(`https://api.figma.com/v1${path}`, {
    headers: { "X-Figma-Token": TOKEN },
    signal: AbortSignal.timeout(60_000),
  });

  if (response.status === 429) {
    const retryAfter = response.headers.get("Retry-After");
    throw new Error(
      `Figma rate limit reached. Retry after ${retryAfter ?? "the suggested wait in Figma"}${retryAfter ? " seconds" : ""}.`,
    );
  }

  const data = await response.json().catch(() => null);
  if (!response.ok || !data || data.error || data.err) {
    throw new Error(
      `Figma request failed (${response.status}): ${data?.message ?? data?.err ?? response.statusText}`,
    );
  }
  return data;
}

async function fetchList(endpoint, key) {
  const data = await figma(`${filePath}/${endpoint}`);
  const items = data.meta?.[key];
  if (!Array.isArray(items)) {
    throw new Error(`Expected an array from ${endpoint}.`);
  }
  return items;
}

function nodeUrl(id) {
  return `https://www.figma.com/design/${encodeURIComponent(FILE_KEY)}?node-id=${encodeURIComponent(id)}`;
}

async function fetchSetDetails(sets) {
  const results = [];
  let version;

  // Batch requests instead of requesting each set separately.
  for (let index = 0; index < sets.length; index += 50) {
    const batch = sets.slice(index, index + 50);
    const query = new URLSearchParams({
      ids: batch.map((set) => set.node_id).join(","),
      depth: "1",
    });
    if (version) query.set("version", version);

    const data = await figma(`${filePath}/nodes?${query}`);
    if (!data.nodes) throw new Error("Missing node data in Figma response.");
    version ??= data.version;

    for (const set of batch) {
      const node = data.nodes[set.node_id]?.document;
      const available = node?.type === "COMPONENT_SET";
      results.push({
        nodeId: set.node_id,
        publishedName: set.name,
        url: nodeUrl(set.node_id),
        fileVersion: data.version ?? null,
        status: available ? "available" : "unavailable",
        currentName: available ? node.name : null,
        propertyDefinitions: available
          ? (node.componentPropertyDefinitions ?? {})
          : null,
        variants: available
          ? (node.children ?? [])
              .filter((child) => child.type === "COMPONENT")
              .map((child) => ({
                nodeId: child.id,
                name: child.name,
                url: nodeUrl(child.id),
              }))
          : null,
      });
    }
  }
  return results;
}

async function generateReport() {
  const components = await fetchList("components", "components");
  const sets = await fetchList("component_sets", "component_sets");
  const styles = await fetchList("styles", "styles");
  const componentSets = await fetchSetDetails(sets);
  const withDescription = components.filter((c) =>
    c.description?.trim(),
  ).length;

  // Variables are optional and require separate API access.
  let variables = { status: "not_requested" };
  if (process.env.INCLUDE_VARIABLES === "true") {
    try {
      const data = await figma(`${filePath}/variables/local`);
      if (!data.meta?.variables || !data.meta?.variableCollections) {
        throw new Error("Missing variable data in Figma response.");
      }
      variables = {
        status: "available",
        items: Object.values(data.meta.variables),
        collections: Object.values(data.meta.variableCollections),
      };
    } catch (error) {
      variables = { status: "unavailable", reason: error.message };
    }
  }

  const report = {
    generatedAt: new Date().toISOString(),
    fileKey: FILE_KEY,
    scope: {
      inventory:
        "Published components, component sets, and styles in one main file",
      details: "File node details for the discovered published sets",
      excludes:
        "Unpublished-only sets, other files, usage analytics, and UX validation",
    },
    summary: {
      publishedComponents: components.length,
      publishedComponentSets: sets.length,
      publishedStyles: styles.length,
      componentsWithDescription: withDescription,
      descriptionPresencePercent: components.length
        ? Math.round((withDescription / components.length) * 100)
        : null,
      unavailableSetDetails: componentSets.filter(
        (set) => set.status === "unavailable",
      ).length,
    },
    components: components.map((c) => ({
      nodeId: c.node_id,
      key: c.key,
      name: c.name,
      description: c.description?.trim() || null,
      containingFrame: c.containing_frame?.name ?? null,
      url: nodeUrl(c.node_id),
    })),
    componentSets,
    styles: styles.map((style) => ({
      key: style.key,
      nodeId: style.node_id,
      name: style.name,
      type: style.style_type,
      description: style.description?.trim() || null,
    })),
    variables,
  };

  const stamp = report.generatedAt.replace(/[:.]/g, "-");
  const filename = `audit-report-${stamp}.json`;
  await writeFile(filename, JSON.stringify(report, null, 2), "utf8");
  console.log(`Saved ${filename}`);
  console.log(report.summary);
}

generateReport().catch((error) => {
  console.error(error.message);
  process.exitCode = 1;
});
