"use strict";
/*
 * Copyright (c) 2025-2026 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = build;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const process_build_config_1 = require("./init/process_build_config");
const build_mode_1 = require("./build/build_mode");
const logger_1 = require("./logger");
const error_1 = require("./util/error");
const generate_arktsconfig_1 = require("./build/generate_arktsconfig");
const plugins_driver_1 = require("./plugins/plugins_driver");
const types_1 = require("./types");
const build_framework_mode_1 = require("./build/build_framework_mode");
const init_koala_modules_1 = require("./init/init_koala_modules");
// NOTE: to be refactored
function backwardCompatibleBuildConfigStub(projectConfig, loggerGetter) {
    if (projectConfig.dependentModuleList) {
        projectConfig.dependencyModuleList = [...projectConfig.dependentModuleList];
    }
    const hvigorLogger = projectConfig.getHvigorConsoleLogger;
    logger_1.Logger.getInstance(hvigorLogger ?? (loggerGetter ?? logger_1.getConsoleLogger));
}
function replaceOnEnv(str, indexA, indexB) {
    let envName = str.substring(indexA + 2, indexB);
    const envValue = process.env[envName] || '';
    if (envValue === '') {
        throw new Error(envName + ' environment variable is not set');
    }
    return str.replace(str.substring(indexA, indexB + 1), envValue);
}
function getVar(str) {
    if (str === null || str === undefined || str === '') {
        return '';
    }
    let indexA = str.indexOf('$');
    let indexB = str.indexOf('}');
    if (indexA === -1 || indexB === -1) {
        return str;
    }
    return replaceOnEnv(str, indexA, indexB);
}
function validatePlugins(projectConfig) {
    for (const key in projectConfig.plugins) {
        projectConfig.plugins[key] = getVar(projectConfig.plugins[key]);
    }
}
function validatePaths(projectConfig) {
    for (const key in projectConfig.paths) {
        for (let i = 0; i < projectConfig.paths[key].length; i++) {
            projectConfig.paths[key][i] = getVar(projectConfig.paths[key][i]);
        }
    }
}
function validateSingleFieldPaths(projectConfig) {
    if (projectConfig.pandaStdlibPath) {
        projectConfig.pandaStdlibPath = getVar(projectConfig.pandaStdlibPath);
    }
    projectConfig.sdkAliasMap = projectConfig.sdkAliasMap instanceof Map
        ? projectConfig.sdkAliasMap
        : new Map(Object.entries(projectConfig.sdkAliasMap || {}));
    projectConfig.moduleRootPath = getVar(projectConfig.moduleRootPath);
    projectConfig.buildSdkPath = getVar(projectConfig.buildSdkPath);
    projectConfig.loaderOutPath = getVar(projectConfig.loaderOutPath);
    projectConfig.cachePath = getVar(projectConfig.cachePath);
    projectConfig.entryFile = getVar(projectConfig.entryFile);
}
function validateInteropApiPaths(interopApiPaths) {
    for (let i = 0; i < interopApiPaths?.length || 0; i++) {
        interopApiPaths[i] = getVar(interopApiPaths[i]);
    }
}
function validateSdkAliasMap(projectConfig) {
    if (projectConfig.sdkAliasMap.size !== 0) {
        for (const [name, path] of projectConfig.sdkAliasMap) {
            const newPath = getVar(path);
            projectConfig.sdkAliasMap.set(name, newPath);
        }
    }
}
function validateCompileFiles(compileFiles) {
    compileFiles.forEach((file, i) => {
        compileFiles[i] = getVar(file);
    });
}
function validateDependencyModuleList(projectConfig) {
    for (let i = 0; i < projectConfig.dependencyModuleList?.length || 0; i++) {
        projectConfig.dependencyModuleList[i].modulePath = getVar(projectConfig.dependencyModuleList[i].modulePath);
        const currentEntryFile = projectConfig.dependencyModuleList[i].entryFile;
        if (currentEntryFile) {
            projectConfig.dependencyModuleList[i].entryFile = getVar(currentEntryFile);
        }
        const currentDeclFilesPath = projectConfig.dependencyModuleList[i].declFilesPath;
        if (currentDeclFilesPath) {
            projectConfig.dependencyModuleList[i].declFilesPath = getVar(currentDeclFilesPath);
        }
        const currentAbcPath = projectConfig.dependencyModuleList[i].abcPath;
        if (currentAbcPath) {
            projectConfig.dependencyModuleList[i].abcPath = getVar(currentAbcPath);
        }
        for (let j = 0; j < projectConfig.dependencyModuleList[i].sourceRoots.length; j++) {
            projectConfig.dependencyModuleList[i].sourceRoots[j] = getVar(projectConfig.dependencyModuleList[i].sourceRoots[j]);
        }
    }
}
function validateDependentModuleList(projectConfig) {
    for (let i = 0; i < projectConfig.dependentModuleList?.length || 0; i++) {
        projectConfig.dependentModuleList[i].modulePath = getVar(projectConfig.dependentModuleList[i].modulePath);
        const currentEntryFile = projectConfig.dependentModuleList[i].entryFile;
        if (currentEntryFile) {
            projectConfig.dependentModuleList[i].entryFile = getVar(currentEntryFile);
        }
        const currentDeclFilesPath = projectConfig.dependentModuleList[i].declFilesPath;
        if (currentDeclFilesPath) {
            projectConfig.dependentModuleList[i].declFilesPath = getVar(currentDeclFilesPath);
        }
        const currentAbcPath = projectConfig.dependentModuleList[i].abcPath;
        if (currentAbcPath) {
            projectConfig.dependentModuleList[i].abcPath = getVar(currentAbcPath);
        }
        for (let j = 0; j < projectConfig.dependentModuleList[i].sourceRoots.length; j++) {
            projectConfig.dependentModuleList[i].sourceRoots[j] = getVar(projectConfig.dependentModuleList[i].sourceRoots[j]);
        }
    }
}
function validateModuleFiles(projectConfig) {
    for (let i = 0; i < projectConfig.moduleFiles?.length || 0; i++) {
        projectConfig.moduleFiles[i].packageName = getVar(projectConfig.moduleFiles[i].packageName);
        for (let j = 0; j < projectConfig.moduleFiles[i].staticFiles?.length || 0; j++) {
            projectConfig.moduleFiles[i].staticFiles[j] = getVar(projectConfig.moduleFiles[i].staticFiles[j]);
        }
    }
}
function validate(projectConfig) {
    validatePlugins(projectConfig);
    validatePaths(projectConfig);
    validateSingleFieldPaths(projectConfig);
    validateInteropApiPaths(projectConfig.interopApiPaths);
    validateSdkAliasMap(projectConfig);
    validateCompileFiles(projectConfig.compileFiles);
    validateDependencyModuleList(projectConfig);
    validateDependentModuleList(projectConfig);
    validateModuleFiles(projectConfig);
}
async function build(projectConfig, loggerGetter) {
    validate(projectConfig);
    backwardCompatibleBuildConfigStub(projectConfig, loggerGetter);
    let logger = logger_1.Logger.getInstance();
    logger.printDebug(`Project config: ${JSON.stringify(projectConfig, null, 1)}`);
    let buildConfig = (0, process_build_config_1.initBuildConfig)(projectConfig);
    try {
        if (projectConfig.frameworkMode === true) {
            let buildframeworkMode = new build_framework_mode_1.BuildFrameworkMode(buildConfig);
            await buildframeworkMode.runSimultaneous();
        }
        else {
            let buildMode = new build_mode_1.BuildMode(buildConfig);
            if (projectConfig.enableDeclgenEts2Ts === true) {
                logger.printInfo('generate Declaration');
                await buildMode.generateDeclarationV1Parallel();
            }
            else if (projectConfig.buildType === types_1.BUILD_TYPE.BUILD) {
                logger.printInfo('just build');
                await buildMode.run();
            }
        }
    }
    catch (error) {
        if (error instanceof error_1.DriverError) {
            logger_1.Logger.getInstance().printErrorAndExit(error.logData);
        }
        else {
            logger_1.Logger.getInstance().printWarn('Error occured');
            logger_1.Logger.getInstance().printWarn('Error is not DriverError');
            throw error;
        }
    }
    finally {
        clean();
    }
}
function clean() {
    logger_1.Logger.destroyInstance();
    generate_arktsconfig_1.ArkTSConfigGenerator.destroyInstance();
    plugins_driver_1.PluginDriver.destroyInstance();
    (0, init_koala_modules_1.cleanKoalaModule)();
}
function main() {
    const buildConfigPath = path.resolve(process.argv[2]);
    const projectConfig = JSON.parse(fs.readFileSync(buildConfigPath, 'utf-8'));
    build(projectConfig);
}
if (require.main === module) {
    main();
}
