import { readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const here = dirname(fileURLToPath(import.meta.url));
const cssPath = resolve(here, "../src/design/tokens/tokens.css");
const outPath = resolve(here, "../src/design/tokens/tokens.ts");

const css = readFileSync(cssPath, "utf8");
const tokenMatches = [...css.matchAll(/--([a-z0-9-]+):\s*([^;]+);/g)];
const tokens = Object.fromEntries(
  tokenMatches.map(([, name, value]) => [name, value.trim()]),
);

const body = `// Generated by scripts/generate-tokens.ts. Do not edit by hand.
export const tokens = ${JSON.stringify(tokens, null, 2)} as const;

export type DesignTokenName = keyof typeof tokens;
export type DesignTokenValue = (typeof tokens)[DesignTokenName];
`;

writeFileSync(outPath, body);
