"use strict";
/*
 * Copyright (c) 2025 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.KitImportTransformer = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const logger_1 = require("../logger");
const error_1 = require("../util/error");
const pre_define_1 = require("../pre_define");
class KitImportTransformer {
    constructor(arkts, program, buildSdkPath, aliasMap) {
        this.extraImports = [];
        this.arkts = arkts;
        this.buildSdkPath = buildSdkPath;
        this.sdkAliasConfig = aliasMap;
        this.program = program;
        this.logger = logger_1.Logger.getInstance();
    }
    transform(astNode) {
        if (!this.arkts.isEtsScript(astNode)) {
            return astNode;
        }
        const newStatements = [];
        const dynamicAliasNames = new Set(this.getDynamicAliasNames());
        if (astNode.statements.length === 0) {
            return astNode;
        }
        for (const stmt of astNode.statements) {
            if (this.arkts.isETSImportDeclaration(stmt) && dynamicAliasNames.has(stmt.source?.str)) {
                this.splitKitImport(stmt);
                continue;
            }
            newStatements.push(stmt);
        }
        const finalStatements = [...this.extraImports, ...newStatements];
        return this.arkts.factory.updateEtsScript(astNode, finalStatements);
    }
    splitKitImport(importNode) {
        const kitName = importNode.source.str;
        const symbolsJson = this.loadKitSymbolsJson(kitName);
        if (!symbolsJson) {
            return;
        }
        const groupedSymbols = this.groupImportSpecifiersBySource(importNode, symbolsJson, kitName);
        this.generateSplitImportDeclarations(groupedSymbols);
    }
    loadKitSymbolsJson(kitName) {
        let jsonFileName = this.getOriginalNameByAlias(kitName);
        if (jsonFileName === '') {
            this.logger.printError(logger_1.LogDataFactory.newInstance(error_1.ErrorCode.BUILDSYSTEM_PLUGIN_ALIAS_CONFIG_PARSING_FAIL, `json file: '${jsonFileName}' not found in kit config contents`));
            return null;
        }
        const configPath = path.resolve(this.buildSdkPath, pre_define_1.KIT_CONFIGS_PATH_FROM_SDK, `${jsonFileName}.json`);
        if (!fs.existsSync(configPath)) {
            this.logger.printError(logger_1.LogDataFactory.newInstance(error_1.ErrorCode.BUILDSYSTEM_PLUGIN_ALIAS_CONFIG_PARSING_FAIL, `Kit config file not found for ${kitName}`, configPath));
            return null;
        }
        try {
            return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
        }
        catch (error) {
            this.logger.printError(logger_1.LogDataFactory.newInstance(error_1.ErrorCode.BUILDSYSTEM_PLUGIN_ALIAS_CONFIG_PARSING_FAIL, `Failed to parse kit config JSON for ${kitName}`, error instanceof Error ? error.message : String(error)));
            return null;
        }
    }
    groupImportSpecifiersBySource(importNode, symbolsJson, kitName) {
        const grouped = new Map();
        for (const specifier of importNode.specifiers) {
            if (!this.arkts.isImportSpecifier(specifier)) {
                continue;
            }
            const symbolName = specifier.imported?.name;
            if (!symbolName) {
                continue;
            }
            const typedSymbols = symbolsJson;
            const symbolEntry = typedSymbols.symbols?.[symbolName];
            if (!symbolEntry?.source) {
                this.logger.printWarn(`Symbol '${symbolName}' not found in ${kitName}.json`);
                continue;
            }
            const sourcePath = pre_define_1.DYNAMIC_PREFIX + symbolEntry.source.replace(/\.d\.ts$/, '');
            if (!grouped.has(sourcePath)) {
                grouped.set(sourcePath, []);
            }
            grouped.get(sourcePath).push(symbolName);
        }
        return grouped;
    }
    generateSplitImportDeclarations(groupedSymbols) {
        for (const [source, names] of groupedSymbols.entries()) {
            const specifiers = names.map(name => this.arkts.factory.createImportSpecifier(this.arkts.factory.createIdentifier(name), this.arkts.factory.createIdentifier(name)));
            const importDecl = this.arkts.factory.createImportDeclaration(this.arkts.factory.createStringLiteral(source), specifiers, this.arkts.Es2pandaImportKinds.IMPORT_KINDS_VALUE, this.program, this.arkts.Es2pandaImportFlags.IMPORT_FLAGS_NONE);
            this.extraImports.push(importDecl);
        }
    }
    getDynamicAliasNames() {
        const dynamicAliasNames = new Set();
        if (Object.keys(this.sdkAliasConfig).length === 0) {
            return dynamicAliasNames;
        }
        for (const innerMap of Object.values(this.sdkAliasConfig)) {
            for (const [aliasName, aliasConfig] of Object.entries(innerMap)) {
                if (!aliasConfig.originalAPIName.startsWith('@kit')) {
                    continue;
                }
                if (!aliasConfig.isStatic) {
                    dynamicAliasNames.add(aliasName);
                }
            }
        }
        return dynamicAliasNames;
    }
    getOriginalNameByAlias(aliasName) {
        for (const innerMap of Object.values(this.sdkAliasConfig)) {
            if (aliasName in innerMap) {
                return innerMap[aliasName].originalAPIName;
            }
        }
        return '';
    }
}
exports.KitImportTransformer = KitImportTransformer;
