#!/usr/bin/env node
/**
 * Generate SnapBack Icon Font
 *
 * This script generates a WOFF icon font from SVG icons for use in VS Code.
 * The icon font enables the $(snapback-icon-name) syntax throughout the extension.
 *
 * Run: node scripts/generate-icon-font.mjs
 *
 * Prerequisites: npm install -D svgtofont
 */

import {
	readFileSync,
	writeFileSync,
	mkdirSync,
	existsSync,
	readdirSync,
} from "node:fs";
import { join, basename, parse } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = fileURLToPath(new URL(".", import.meta.url));
const ROOT_DIR = join(__dirname, "..");
const ICONS_DIR = join(ROOT_DIR, "media", "icons");
const OUTPUT_DIR = join(ROOT_DIR, "media", "fonts");

// Icon mapping with Unicode codepoints
const ICON_MAP = {
	"snapback-shield": {
		codepoint: "\\E001",
		description: "SnapBack protection status",
	},
	"snapback-lightning": {
		codepoint: "\\E002",
		description: "AI-attributed change",
	},
	"snapback-pulse": {
		codepoint: "\\E003",
		description: "Active session pulse",
	},
	"snapback-brain": {
		codepoint: "\\E004",
		description: "Intelligence/learning",
	},
	"snapback-rollback": {
		codepoint: "\\E005",
		description: "Rollback available",
	},
	"snapback-risk": { codepoint: "\\E006", description: "Risk indicator" },
};

/**
 * Generate CSS for the icon font
 */
function generateIconFontCss(fontName, icons) {
	const iconDefinitions = Object.entries(icons)
		.map(([name, { codepoint }]) => {
			const className = name.replace("snapback-", "");
			return `.snapback-${className}:before { content: "${codepoint}"; }`;
		})
		.join("\n");

	return `
@font-face {
  font-family: "${fontName}";
  src: url("./${fontName}.woff2") format("woff2"),
       url("./${fontName}.woff") format("woff");
  font-weight: normal;
  font-style: normal;
  font-display: block;
}

.snapback-icon {
  font-family: "${fontName}" !important;
  speak: never;
  font-style: normal;
  font-weight: normal;
  font-variant: normal;
  text-transform: none;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

${iconDefinitions}
`;
}

/**
 * Generate package.json contributes.icons section
 */
function generateIconsContribution(icons) {
	const contributions = {};

	for (const [name, { codepoint, description }] of Object.entries(icons)) {
		contributions[name] = {
			description,
			default: {
				fontPath: "./media/fonts/snapback-icons.woff",
				fontCharacter: codepoint,
			},
		};
	}

	return contributions;
}

/**
 * Create a simple SVG to font conversion
 * Note: For production, use a proper tool like svgtofont or fantasticon
 */
async function generateIconFont() {
	console.log("🎨 Generating SnapBack icon font...\n");

	// Ensure output directory exists
	if (!existsSync(OUTPUT_DIR)) {
		mkdirSync(OUTPUT_DIR, { recursive: true });
	}

	// Read all SVG files
	const svgFiles = readdirSync(ICONS_DIR)
		.filter((f) => f.endsWith(".svg"))
		.map((f) => join(ICONS_DIR, f));

	console.log(`Found ${svgFiles.length} SVG icons:`);
	svgFiles.forEach((f) => console.log(`  - ${basename(f)}`));
	console.log();

	// Generate CSS
	const css = generateIconFontCss("snapback-icons", ICON_MAP);
	writeFileSync(join(OUTPUT_DIR, "snapback-icons.css"), css);
	console.log("✓ Generated snapback-icons.css");

	// Generate contributions snippet
	const contributions = generateIconsContribution(ICON_MAP);
	const contributionsJson = JSON.stringify(
		{ contributes: { icons: contributions } },
		null,
		2
	);
	writeFileSync(
		join(OUTPUT_DIR, "icons-contribution.json"),
		contributionsJson
	);
	console.log("✓ Generated icons-contribution.json (add to package.json)");

	// Generate TypeScript icon constants
	const tsConstants = `/**
 * SnapBack Icon Constants
 * Auto-generated from icon font
 */

export const SNAPBACK_ICONS = {
  SHIELD: "$(snapback-shield)",
  LIGHTNING: "$(snapback-lightning)",
  PULSE: "$(snapback-pulse)",
  BRAIN: "$(snapback-brain)",
  ROLLBACK: "$(snapback-rollback)",
  RISK: "$(snapback-risk)",
} as const;

export type SnapBackIcon = typeof SNAPBACK_ICONS[keyof typeof SNAPBACK_ICONS];
`;
	writeFileSync(join(ROOT_DIR, "src", "constants", "icons.ts"), tsConstants);
	console.log("✓ Generated src/constants/icons.ts");

	console.log("\n📝 Next steps:");
	console.log("1. Install svgtofont: pnpm add -D svgtofont");
	console.log(
		"2. Run: npx svgtofont --sources media/icons --output media/fonts"
	);
	console.log(
		"3. Add the icons contribution from media/fonts/icons-contribution.json to package.json"
	);
	console.log(
		"\nAlternatively, use the codicon fallback icons already defined in the codebase."
	);
}

// Run the generator
generateIconFont().catch(console.error);
