#!/usr/bin/env node
/**
 * Convert SVG to PNG using sharp
 * Usage: node convert-svg-with-sharp.js <input.svg> <output.png> <width> <height>
 */

const fs = require('fs');
const path = require('path');

// Try to find sharp in various locations
let sharp;
try {
  sharp = require('sharp');
} catch (e) {
  // Try packages/auth/node_modules/sharp
  const authSharpPath = path.join(__dirname, '../../packages/auth/node_modules/sharp');
  if (fs.existsSync(authSharpPath)) {
    sharp = require(authSharpPath);
  } else {
    // Try root node_modules/sharp
    const rootSharpPath = path.join(__dirname, '../../node_modules/sharp');
    if (fs.existsSync(rootSharpPath)) {
      sharp = require(rootSharpPath);
    } else {
      console.error('Error: sharp module not found. Install with: pnpm add sharp');
      process.exit(1);
    }
  }
}

const [,, inputFile, outputFile, width, height] = process.argv;

if (!inputFile || !outputFile) {
  console.error('Usage: node convert-svg-with-sharp.js <input.svg> <output.png> <width> <height>');
  process.exit(1);
}

const inputPath = path.resolve(inputFile);
const outputPath = path.resolve(outputFile);
const widthNum = parseInt(width || '200', 10);
const heightNum = parseInt(height || '200', 10);

if (!fs.existsSync(inputPath)) {
  console.error(`Error: Input file not found: ${inputPath}`);
  process.exit(1);
}

// Ensure output directory exists
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

sharp(inputPath)
  .resize(widthNum, heightNum)
  .png()
  .toFile(outputPath)
  .then(() => {
    console.log(`Success: ${outputPath}`);
    process.exit(0);
  })
  .catch((error) => {
    console.error(`Error converting ${inputPath}:`, error.message);
    process.exit(1);
  });

