const fs = require('fs')
const path = require('path')
const { optimize } = require('svgo')

// Configuration for SVGO
const svgoConfig = {
  multipass: true,
  plugins: [
    'preset-default',
    'removeDimensions',
    'removeViewBox',
    {
      name: 'removeAttrs',
      params: {
        attrs: '(fill|stroke)'
      }
    }
  ]
}

// Function to minify a single SVG file
async function minifySvg(filePath) {
  try {
    const svgContent = fs.readFileSync(filePath, 'utf8')
    const result = optimize(svgContent, svgoConfig)

    if (result.error) {
      console.error(`Error minifying ${filePath}:`, result.error)
      return
    }

    const minifiedPath = filePath.replace('.svg', '.min.svg')
    fs.writeFileSync(minifiedPath, result.data)
    console.log(`Created minified version: ${minifiedPath}`)
  } catch (error) {
    console.error(`Error processing ${filePath}:`, error)
  }
}

// Function to process all SVG files in a directory
async function processDirectory(directory) {
  try {
    const files = fs.readdirSync(directory)

    for (const file of files) {
      const filePath = path.join(directory, file)
      const stat = fs.statSync(filePath)

      if (stat.isDirectory()) {
        await processDirectory(filePath)
      } else if (file.endsWith('.svg') && !file.endsWith('.min.svg')) {
        await minifySvg(filePath)
      }
    }
  } catch (error) {
    console.error(`Error processing directory ${directory}:`, error)
  }
}

// Main execution
const iconsDirectory = path.join(__dirname, '..', 'src', 'assets', 'icons')

if (!fs.existsSync(iconsDirectory)) {
  console.error(`Directory not found: ${iconsDirectory}`)
  process.exit(1)
}

console.log('Starting SVG minification...')
processDirectory(iconsDirectory)
  .then(() => console.log('SVG minification completed!'))
  .catch((error) => {
    console.error('Error during minification:', error)
    process.exit(1)
  })
