"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.copyModifications = copyModifications;
const path_1 = require("path");
const logger_1 = require("../../utils/logger");
const fs_1 = require("fs");
const error_handler_1 = require("../../utils/error.handler");
const logger = logger_1.Logger.getInstance("component.config");
async function copyModifications(baseDir, componentJsonPath) {
    const configJSON = JSON.parse((0, fs_1.readFileSync)(componentJsonPath, 'utf-8'));
    logger.debug(`Component configuration is ${JSON.stringify(configJSON, null, 4)}`);
    const modifications = configJSON.postInstall?.modifications ?? [];
    if (!modifications || modifications.length === 0) {
        logger.debug(`No modifications provided - skipping`);
        return;
    }
    const dirName = (0, path_1.dirname)(baseDir);
    logger.debug(`Copying ${modifications.length} modification(s) for component ${dirName} ...`);
    // Copy each modification
    for (const config of modifications) {
        const srcPath = (0, path_1.join)(baseDir, config.source);
        const destPath = (0, path_1.join)(process.cwd(), config.destination);
        logger.debug(`Copying modification from ${srcPath} to ${destPath}`);
        try {
            // Check if source exists
            if (!(0, fs_1.existsSync)(srcPath)) {
                logger.warn(`Source path does not exist: ${srcPath} - skipping`);
                continue;
            }
            // Get source stats to determine if it's a file or directory
            const srcStats = (0, fs_1.statSync)(srcPath);
            if (srcStats.isFile()) {
                // Handle file copying
                copyFile(srcPath, destPath);
            }
            else if (srcStats.isDirectory()) {
                // Handle directory copying
                copyDirectory(srcPath, destPath);
            }
            else {
                logger.warn(`Source is neither file nor directory: ${srcPath} - skipping`);
                continue;
            }
            logger.debug(`Successfully copied ${config.source} to ${config.destination}`);
        }
        catch (error) {
            logger.error(`Failed to copy ${config.source} to ${config.destination}: ${error}`);
            throw new error_handler_1.CLIError(`Failed to copy modification for ${dirName}: ${error}`, { code: error_handler_1.ErrorCode.FILE_SYSTEM_ERROR });
        }
    }
    logger.debug(`Copied ${modifications.length} post install modifications for component ${baseDir} successfully!`);
}
/**
 * Copy a single file, creating destination directory if needed
 */
function copyFile(srcPath, destPath) {
    // Ensure destination directory exists
    const destDir = (0, path_1.dirname)(destPath);
    if (!(0, fs_1.existsSync)(destDir)) {
        (0, fs_1.mkdirSync)(destDir, { recursive: true });
        logger.debug(`Created destination directory: ${destDir}`);
    }
    // Copy the file
    (0, fs_1.copyFileSync)(srcPath, destPath);
    logger.debug(`Copied file: ${srcPath} → ${destPath}`);
}
/**
 * Copy a directory recursively, wiping out target first if it exists
 */
function copyDirectory(srcPath, destPath) {
    // If destination exists, remove it completely
    if ((0, fs_1.existsSync)(destPath)) {
        logger.debug(`Removing existing destination directory: ${destPath}`);
        (0, fs_1.rmSync)(destPath, { recursive: true, force: true });
    }
    // Create destination directory
    (0, fs_1.mkdirSync)(destPath, { recursive: true });
    logger.debug(`Created destination directory: ${destPath}`);
    // Copy all contents recursively
    copyDirectoryContents(srcPath, destPath);
}
/**
 * Recursively copy directory contents
 */
function copyDirectoryContents(srcDir, destDir) {
    const items = (0, fs_1.readdirSync)(srcDir);
    for (const item of items) {
        const srcItemPath = (0, path_1.join)(srcDir, item);
        const destItemPath = (0, path_1.join)(destDir, item);
        const itemStats = (0, fs_1.statSync)(srcItemPath);
        if (itemStats.isFile()) {
            (0, fs_1.copyFileSync)(srcItemPath, destItemPath);
            logger.debug(`Copied file: ${srcItemPath} → ${destItemPath}`);
        }
        else if (itemStats.isDirectory()) {
            (0, fs_1.mkdirSync)(destItemPath, { recursive: true });
            copyDirectoryContents(srcItemPath, destItemPath);
        }
    }
}
//# sourceMappingURL=component.config.js.map