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

const rootDir = path.resolve(__dirname, '..')
const distDir = path.join(rootDir, 'dist')
const sourceDirs = ['src', 'spec']
const sourceFiles = ['package.json', 'package-lock.json', '.env', 'eslint.config.js']
const buildInfoPath = path.join(distDir, 'build-info.json')

function ensureCleanDir(dirPath) {
    fs.rmSync(dirPath, { recursive: true, force: true })
    fs.mkdirSync(dirPath, { recursive: true })
}

function copyRecursive(sourcePath, targetPath) {
    const stats = fs.statSync(sourcePath)

    if (stats.isDirectory()) {
        fs.mkdirSync(targetPath, { recursive: true })
        for (const entry of fs.readdirSync(sourcePath)) {
            copyRecursive(
                path.join(sourcePath, entry),
                path.join(targetPath, entry)
            )
        }
        return
    }

    fs.mkdirSync(path.dirname(targetPath), { recursive: true })
    fs.copyFileSync(sourcePath, targetPath)
}

function build() {
    ensureCleanDir(distDir)

    for (const dir of sourceDirs) {
        const sourcePath = path.join(rootDir, dir)
        if (fs.existsSync(sourcePath)) {
            copyRecursive(sourcePath, path.join(distDir, dir))
        }
    }

    for (const file of sourceFiles) {
        const sourcePath = path.join(rootDir, file)
        if (fs.existsSync(sourcePath)) {
            copyRecursive(sourcePath, path.join(distDir, file))
        }
    }

    fs.writeFileSync(
        buildInfoPath,
        JSON.stringify(
            {
                buildTime: new Date().toISOString(),
            },
            null,
            2
        )
    )

    console.log('Build completed. Deployable files generated in dist/.')
}

build()
