const fs = require('node:fs')
const path = require('node:path')
const { execSync } = require('node:child_process')

// Function to copy a file from source to destination
function copyFile(src, dest) {
  fs.mkdirSync(path.dirname(dest), { recursive: true })
  fs.copyFileSync(src, dest)
  console.log(`Copied ${src} to ${dest}`)
}

// Function to copy all files in a directory recursively
function copyDirectory(srcDir, destDir) {
  const entries = fs.readdirSync(srcDir, { withFileTypes: true })

  for (let entry of entries) {
    const srcPath = path.join(srcDir, entry.name)
    const destPath = path.join(destDir, entry.name)

    if (entry.isDirectory()) {
      copyDirectory(srcPath, destPath)
    }
    else {
      copyFile(srcPath, destPath)
    }
  }
}

// Function to modify package.json to add a new script
function addScriptToPackageJson(scriptName, scriptCommand) {
  const packageJsonPath = path.join(process.env.INIT_CWD, 'package.json')
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))

  packageJson.scripts = packageJson.scripts || {}
  packageJson.scripts[scriptName] = scriptCommand

  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
  console.log(`Added script "${scriptName}": "${scriptCommand}" to package.json`)
}

// Function to run npm run codegen safely
function runCodegen(projectRoot) {
  try {
    execSync('npm run codegen', { cwd: projectRoot, stdio: 'inherit' })
    console.log('Successfully ran npm run codegen')
  }
  catch (error) {
    console.log('npm run codegen failed or script not found, continuing...')
  }
}

if (process.env.INIT_CWD === process.cwd()) process.exit()

// Define source and destination directories
const srcDir = path.join(__dirname, '..', 'templates')
const destDir = process.env.INIT_CWD // Project root

// Copy all files from templates directory to project root
copyDirectory(srcDir, destDir)

// Add new script to package.json
addScriptToPackageJson('codegen', 'graphql-codegen --require dotenv/config --config ./.codegen/codegen.ts dotenv_config_path=.env')

// Run npm run codegen safely
if (!fs.existsSync(path.join(destDir, 'types', 'graphql.ts')) || !fs.existsSync(path.join(destDir, 'composables', 'graphqlObject.ts'))) {
  if (process.env.NUXT_PUBLIC_WS_GRAPHQL) runCodegen(destDir)
}
else {
  console.log('Skipping codegen')
}
