#!/usr/bin/env node

import {
  copyFileSync,
  existsSync,
  mkdirSync,
  readFileSync,
  writeFileSync,
} from 'fs'
import { basename, dirname, resolve } from 'path'
import { fileURLToPath } from 'url'

const __dirname = dirname(fileURLToPath(import.meta.url))
const projectRoot = process.cwd()
const projectName = basename(projectRoot)
const templatesDir = resolve(__dirname, '../templates')
const packageJsonPath = resolve(projectRoot, 'package.json')

console.log('📦 Initializing new component project...')

if (!existsSync(packageJsonPath)) {
  console.error('❌ No package.json found. Run "npm init -y" first.')
  process.exit(1)
}

const srcDir = resolve(projectRoot, 'src')
const appDir = resolve(srcDir, 'app')
const publicDir = resolve(projectRoot, 'public')
const folders = [srcDir, appDir, publicDir]

folders.forEach(dir => {
  if (!existsSync(dir)) {
    mkdirSync(dir, { recursive: true })
  }
})

const templateFiles = {
  'src/app/App.tsx': 'App.tsx',
  'src/config.ts': 'config.ts',
  'src/dataOptions.ts': 'dataOptions.ts',
  'src/viewOptions.ts': 'viewOptions.ts',
  'public/icon.svg': 'icon.svg',
  'tsconfig.json': 'tsconfig.json',
  '.gitignore': '.gitignore',
}

for (const [dest, template] of Object.entries(templateFiles)) {
  const destPath = resolve(projectRoot, dest)
  const templatePath = resolve(templatesDir, template)

  if (existsSync(templatePath) && !existsSync(destPath)) {
    if (dest.includes('src')) {
      const newCode = updateTypesPath(templatePath)
      writeFileSync(destPath, newCode)
    } else {
      copyFileSync(templatePath, destPath)
    }
  }
}

updatePackageJson(projectRoot)

console.log('✅ Project initialized successfully!')
console.log('\nNext steps:')
console.log('  1. yarn run dev')
console.log('  2. yarn run build')

//////

function updatePackageJson(projectRoot) {
  const packageJsonPath = resolve(projectRoot, 'package.json')
  const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'))

  packageJson.scripts = {
    'start:dev': 'bmdl-sdk dev',
    build: 'bmdl-sdk build',
  }

  writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
}

//

function updateTypesPath(filePath) {
  const fileCode = readFileSync(filePath, 'utf-8')

  let finalCode = fileCode.replace("from '../'", "from 'bmdl-sdk'")
  finalCode = finalCode.replace(
    /NameComponent/g,
    kebabToCapitalize(`${projectName}-component`),
  )

  return finalCode
}

//

function kebabToCapitalize(str) {
  return str
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join('')
}
