"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = void 0;
const { Command } = require("commander");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const chalk = require("chalk");
const { execa } = require("execa");
const getPackageManager_js_1 = require("../lib/getPackageManager.js");
const spinner_js_1 = require("../lib/spinner.js");
const index_js_1 = require("../constants/index.js");
exports.init = new Command()
    .name("init")
    .description("initialize Aura UI into your project")
    // .argument // Not supporting to add components while initializing aura-ui. If needed use this to optionally accept the components to add
    .action(() => __awaiter(void 0, void 0, void 0, function* () {
    const cwd = process.cwd();
    const configFilePath = path_1.default.join(cwd, "aura-ui.config.json");
    const spinner = (0, spinner_js_1.getSpinner)("Initializing Aura UI");
    try {
        // Skip if config file exists
        if (fs_1.default.existsSync(configFilePath)) {
            console.log(chalk.yellow("⚠️  Config file already exists. Skipping."));
            return;
        }
        spinner.start();
        // Create config file if it doesn't exist
        fs_1.default.writeFileSync(configFilePath, index_js_1.DEFAULT_CONFIG_FILE_CONTENT);
        yield addInitialSetup(cwd);
        updateGlobalCSS(cwd);
        console.log(chalk.green("Config file created successfully"));
        spinner.succeed("Aura UI initialized successfully.");
        console.log("You can now run `npx aura-ui add componentName` to add components to your project");
    }
    catch (error) {
        spinner.fail("Error while initializing Aura UI to your project.");
        console.log(chalk.yellow("Please try again. If the issue still persists contact the creater of this (btw thats me 😁)"));
        console.error(error);
    }
}));
const addInitialSetup = (cwd) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const libPath = path_1.default.join(cwd, "src", "lib");
        // Create lib dir if it doesn't exist
        if (!fs_1.default.existsSync(libPath)) {
            fs_1.default.mkdirSync(libPath, { recursive: true });
        }
        const CNFunctionFilePath = path_1.default.join(libPath, "utils.ts");
        // Write the cn function file
        fs_1.default.writeFileSync(CNFunctionFilePath, index_js_1.CN_FUNCTION_FILE_CONTENT);
        const packageManager = yield (0, getPackageManager_js_1.getPackageManager)(cwd);
        try {
            yield execa(packageManager, [
                packageManager === "npm" ? "install" : "add",
                ...(packageManager === "deno"
                    ? index_js_1.INITIAL_REQUIRED_DEPENDENCIES.map((dep) => `npm:${dep}`)
                    : index_js_1.INITIAL_REQUIRED_DEPENDENCIES),
            ], {
                cwd,
            });
            console.log(chalk.green("Successfully installed required dependencies"));
        }
        catch (error) {
            console.log(chalk.red(`Failed to install dependencies: ${error.message}`));
            console.log(chalk.yellow("You may need to install these packages manually:"));
            console.log(chalk.yellow("- class-variance-authority"));
            console.log(chalk.yellow("- tailwind-merge"));
            process.exit(1);
        }
    }
    catch (error) {
        console.log("Error while Initializing the setup E:", error.message);
        throw error;
    }
});
const updateGlobalCSS = (cwd) => {
    const possiblePaths = [
        "src/app/globals.css",
        "src/styles/globals.css",
        "styles/globals.css",
        "globals.css"
    ];
    for (const relPath of possiblePaths) {
        try {
            const fullPath = path_1.default.join(cwd, relPath);
            if (!fs_1.default.existsSync(fullPath))
                continue;
            const existingContent = fs_1.default.readFileSync(fullPath, "utf-8");
            const updatedContent = `${index_js_1.GLOBAL_CSS_VARS.trim()}\n\n${existingContent}`;
            fs_1.default.writeFileSync(fullPath, updatedContent);
            return;
        }
        catch (error) {
            console.log(chalk.red("Error occured while updating global css vars. You have add css vars yourself."));
        }
    }
};
