/**
 * Bookmarklet Generator
 *
 * Converts a regular JavaScript file into a bookmarklet format.
 * - Removes all comments (single-line and multi-line)
 * - Wraps code in IIFE for bookmarklet format
 * - Minifies to a single line
 * - Copies to clipboard
 *
 * Usage:
 *   node code/utils/bookmarkletMaker.js <path-to-js-file>
 *   npm run bookmarklet -- <path-to-js-file>
 *
 * Example:
 *   npm run bookmarklet -- code/bookmarklets/example-bookmarklet.js
 */
import fs from "fs";
import path from "path";
import clipboardy from "clipboardy";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * Remove all comments from JavaScript code
 * @param {string} code - The JavaScript code
 * @returns {string} Code without comments
 */
function removeComments(code) {
  // Remove multi-line comments /* ... */
  code = code.replace(/\/\*[\s\S]*?\*\//g, "");
  // Remove single-line comments //
  code = code.replace(/\/\/.*$/gm, "");
  return code;
}

/**
 * Minify code to a single line
 * @param {string} code - The JavaScript code
 * @returns {string} Minified code
 */
function minify(code) {
  return code
    .split("\n")
    .map((line) => line.trim())
    .filter((line) => line.length > 0)
    .join(" ")
    .replace(/\s+/g, " ")
    .replace(/\s*([{}();,])\s*/g, "$1");
}

/**
 * Generate bookmarklet from JavaScript file
 * @param {string} filePath - Path to the JavaScript file
 * @returns {string} The bookmarklet code
 */
function generateBookmarklet(filePath) {
  // Validate file exists
  if (!fs.existsSync(filePath)) {
    throw new Error(`File not found: ${filePath}`);
  }

  // Read the JavaScript file
  const jsCode = fs.readFileSync(filePath, "utf8");

  // Clean and minify
  let cleanedCode = removeComments(jsCode);
  cleanedCode = minify(cleanedCode);

  // Wrap in IIFE and add javascript: protocol
  const bookmarklet = `javascript:(function(){${cleanedCode}})();`;

  return bookmarklet;
}

// Main execution
try {
  const filePath = process.argv[2];

  if (!filePath) {
    console.error("❌ Error: Please provide a file path");
    console.log("\nUsage:");
    console.log("  npm run bookmarklet -- <path-to-js-file>");
    console.log("\nExample:");
    console.log("  npm run bookmarklet -- code/bookmarklets/my-bookmarklet.js");
    process.exit(1);
  }

  const bookmarklet = generateBookmarklet(filePath);
  const fileName = path.basename(filePath);

  // Copy to clipboard
  clipboardy.writeSync(bookmarklet);

  console.log("✅ Bookmarklet generated successfully!");
  console.log(`📁 Source: ${fileName}`);
  console.log(`📋 Copied to clipboard (${bookmarklet.length} characters)`);
  console.log("\n📝 Next steps:");
  console.log("  1. Create a new bookmark in your browser");
  console.log("  2. Paste the clipboard content as the URL");
  console.log("  3. Give it a name and save");
} catch (error) {
  console.error("❌ Error:", error.message);
  process.exit(1);
}
