import fs from 'node:fs';
import path from 'node:path';
import { parseArgs } from 'node:util';

/**
 * Usage:
 * pnpm build:format-tokens --app=path/to/app.json --palette=path/to/palette.json
 */

// Parse command line arguments
const { values } = parseArgs({
  args: process.argv.slice(2),
  options: {
    app: {
      type: 'string',
    },
    palette: {
      type: 'string',
    },
  },
});

if (!values.app || !values.palette) {
  console.error('Error: Both --app and --palette arguments are required.');
  process.exit(1);
}

const appPath = path.resolve(process.cwd(), values.app);
const palettePath = path.resolve(process.cwd(), values.palette);

// Verify files exist
if (!fs.existsSync(appPath)) {
  console.error(`Error: App file not found at ${appPath}`);
  process.exit(1);
}
if (!fs.existsSync(palettePath)) {
  console.error(`Error: Palette file not found at ${palettePath}`);
  process.exit(1);
}

// Ensure output directory exists
const outputDir = path.resolve(process.cwd(), 'tokens/color');
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

/**
 * Recursively formats the token object:
 * - Deletes "prefix" keys
 * - Renames "value" to "$value"
 * - Renames "type" to "$type"
 */
function formatTokens(obj: any): any {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }

  if (Array.isArray(obj)) {
    return obj.map(formatTokens);
  }

  const newObj: any = {};

  for (const key of Object.keys(obj)) {
    if (key === 'prefix') {
      continue;
    }

    let newKey = key;
    if (key === 'value') {
      newKey = '$value';
    } else if (key === 'type') {
      newKey = '$type';
    }

    newObj[newKey] = formatTokens(obj[key]);
  }

  return newObj;
}

try {
  // Process app.json
  console.log(`Processing app configuration from ${values.app}...`);
  const appContent = fs.readFileSync(appPath, 'utf-8');
  const appData = JSON.parse(appContent);

  for (const [key, value] of Object.entries(appData)) {
    if (typeof value !== 'object' || value === null) {
      console.warn(`Warning: Root key "${key}" in app.json is not an object. Skipping.`);
      continue;
    }

    const formattedValue = formatTokens(value);
    const outputPath = path.join(outputDir, `${key}.json`);

    fs.writeFileSync(outputPath, JSON.stringify(formattedValue, null, 2) + '\n');
    console.log(`Written ${outputPath}`);
  }

  // Process palette.json
  console.log(`Processing palette configuration from ${values.palette}...`);
  const paletteContent = fs.readFileSync(palettePath, 'utf-8');
  const paletteData = JSON.parse(paletteContent);

  const formattedPalette = formatTokens(paletteData);
  const paletteOutputPath = path.join(outputDir, 'palette.json');

  fs.writeFileSync(paletteOutputPath, JSON.stringify(formattedPalette, null, 2) + '\n');
  console.log(`Written ${paletteOutputPath}`);

  console.log('Done.');
} catch (error) {
  console.error('An error occurred:', error);
  process.exit(1);
}
