"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.init = init;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const cross_spawn_1 = __importDefault(require("cross-spawn"));
const validate_npm_package_name_1 = __importDefault(require("validate-npm-package-name"));
const ora_1 = __importDefault(require("ora"));
const chalk_1 = __importDefault(require("chalk"));
const logger_1 = require("../utils/logger");
const prompt_1 = require("../utils/prompt");
const template_1 = require("../utils/template");
const file_1 = require("../utils/file");
const dependencies_1 = require("../constants/dependencies");
const projectApi_1 = require("../utils/projectApi");
const cache_1 = require("../utils/cache");
async function init(projectName, options) {
    (0, logger_1.printBanner)();
    // 1. 验证项目名称
    const validationResult = (0, validate_npm_package_name_1.default)(projectName);
    if (!validationResult.validForNewPackages) {
        logger_1.logger.error(`项目名称无效: ${projectName}`);
        if (validationResult.errors) {
            validationResult.errors.forEach((err) => console.log(`  - ${err}`));
        }
        if (validationResult.warnings) {
            validationResult.warnings.forEach((warn) => console.log(`  - ${warn}`));
        }
        process.exit(1);
    }
    const targetDir = path_1.default.resolve(process.cwd(), projectName);
    // 2. 检查目标目录
    if (fs_extra_1.default.existsSync(targetDir)) {
        if (options.force) {
            logger_1.logger.warn(`强制覆盖目录: ${targetDir}`);
            await fs_extra_1.default.remove(targetDir);
        }
        else {
            const overwrite = await (0, prompt_1.promptOverwrite)();
            if (!overwrite) {
                logger_1.logger.info('操作已取消');
                process.exit(0);
            }
            await fs_extra_1.default.remove(targetDir);
        }
    }
    // 3. 收集用户输入
    let answers;
    // 如果命令行已提供 authorization，跳过交互式输入
    if (options.authorization) {
        answers = {
            authorization: options.authorization,
            description: options.description || '',
            minorVersionDescription: options.minorVersionDescription || '',
            revisionVersionDescription: options.revisionVersionDescription || '',
            author: options.author || '',
            appId: options.appId || '',
            appName: '',
        };
        // 保存到缓存
        await (0, cache_1.saveAuthorization)(options.authorization);
    }
    else {
        answers = await (0, prompt_1.promptInitOptions)(projectName);
    }
    // 4. 通过 API 创建 projectVersionId
    const apiSpinner = (0, ora_1.default)('正在创建项目版本...').start();
    let projectVersionId;
    let projectId;
    try {
        const result = await (0, projectApi_1.createProjectVersionId)(projectName, // msId/pid
        answers.authorization, answers.appId || undefined, answers.description, answers.minorVersionDescription, answers.revisionVersionDescription);
        projectVersionId = result.projectVersionId;
        projectId = result.projectId;
        apiSpinner.succeed(`项目版本创建成功: ${projectVersionId}`);
    }
    catch (error) {
        apiSpinner.fail('项目版本创建失败');
        if ((0, cache_1.isAuthorizationInvalidError)(error)) {
            await (0, cache_1.clearAuthorizationCache)();
        }
        logger_1.logger.error(error.message || '未知错误');
        logger_1.logger.info('请检查 authorization 是否正确，或网络连接是否正常');
        process.exit(1);
    }
    // 5. 创建模板数据
    const templateData = (0, template_1.createTemplateData)(projectName, projectVersionId, answers.authorization, {
        description: answers.description,
        author: answers.author,
        isSimple: false,
        features: {
            sharedLib: false,
            redis: false,
            mq: false,
            uts: false,
        },
    });
    // 6. 选择模板目录
    const templateName = 'full';
    const templateDir = (0, file_1.getTemplateDir)(templateName);
    // 检查模板目录是否存在
    if (!fs_extra_1.default.existsSync(templateDir)) {
        logger_1.logger.error(`模板目录不存在: ${templateDir}`);
        logger_1.logger.info('请先创建模板文件');
        process.exit(1);
    }
    // 7. 生成项目
    const spinner = (0, ora_1.default)('正在生成项目...').start();
    try {
        await (0, template_1.renderTemplate)(templateDir, targetDir, templateData);
        spinner.succeed('项目文件生成完成');
    }
    catch (error) {
        spinner.fail('项目文件生成失败');
        throw error;
    }
    // 8. 更新 package.json
    const packageJsonPath = path_1.default.join(targetDir, 'package.json');
    const packageJson = await fs_extra_1.default.readJson(packageJsonPath);
    packageJson.name = projectName;
    packageJson.description = answers.description;
    packageJson.author = answers.author;
    // 设置依赖
    packageJson.dependencies = {
        ...dependencies_1.BASE_DEPENDENCIES,
    };
    Object.assign(packageJson.dependencies, dependencies_1.INTERNAL_DEPENDENCIES);
    // 设置开发依赖
    packageJson.devDependencies = dependencies_1.DEV_DEPENDENCIES;
    // 设置 uploadConfig
    packageJson.uploadConfig = {
        ...dependencies_1.UPLOAD_CONFIG,
        projectVersionId: projectVersionId,
        projectId: projectId || '',
        authorization: answers.authorization,
    };
    await fs_extra_1.default.writeJson(packageJsonPath, packageJson, { spaces: 2 });
    logger_1.logger.success('package.json 配置完成');
    // 9. 安装依赖
    if (!options.skipInstall) {
        const installSpinner = (0, ora_1.default)('正在安装依赖...').start();
        try {
            const registry = options.registry || 'https://dev365.keytop.cn/nexus/repository/npm-group/';
            await installDependencies(targetDir, registry);
            installSpinner.succeed('依赖安装完成');
        }
        catch (error) {
            installSpinner.fail('依赖安装失败');
            logger_1.logger.warn('请手动运行: pnpm install');
        }
    }
    // 10. 输出成功信息
    logger_1.logger.newline();
    logger_1.logger.success(chalk_1.default.green('项目创建成功!'));
    console.log();
    console.log(chalk_1.default.cyan('📁 项目位置:'), targetDir);
    console.log(chalk_1.default.cyan('📦 项目名称:'), projectName);
    console.log(chalk_1.default.cyan('📋 版本类型:'), '完整版');
    if (answers.appName) {
        console.log(chalk_1.default.cyan('🏢 所属应用:'), answers.appName);
    }
    console.log();
    console.log(chalk_1.default.yellow('下一步操作:'));
    console.log(chalk_1.default.gray(`  cd ${projectName}`));
    console.log(chalk_1.default.gray('  pnpm run dev'));
    console.log();
    // console.log(chalk.gray('查看完整使用指南: https://dev365.keytop.cn/nexus/#browse/browse:npm-hosted:midplatform-non-cli'));
    // console.log();
}
function installDependencies(targetDir, registry) {
    return new Promise((resolve, reject) => {
        const child = (0, cross_spawn_1.default)('pnpm', ['install', '--registry', registry], {
            cwd: targetDir,
            stdio: 'inherit',
            shell: true,
        });
        child.on('close', (code) => {
            if (code === 0) {
                resolve();
            }
            else {
                reject(new Error(`pnpm install 失败，退出码: ${code}`));
            }
        });
        child.on('error', (err) => {
            reject(err);
        });
    });
}
//# sourceMappingURL=init.js.map