import { access, readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
export const BRIDGE_PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
function isRecord(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function getPackageDirectory(packageName, packageRoot) {
    return path.join(packageRoot, 'node_modules', ...packageName.split('/'));
}
function resolveConditionalExport(value) {
    if (typeof value === 'string') {
        return value;
    }
    if (!isRecord(value)) {
        return null;
    }
    for (const condition of ['import', 'module', 'default', 'node']) {
        const resolved = resolveConditionalExport(value[condition]);
        if (resolved) {
            return resolved;
        }
    }
    return null;
}
function resolvePackageRootExport(exportsField) {
    if (typeof exportsField === 'string') {
        return exportsField;
    }
    if (!isRecord(exportsField)) {
        return null;
    }
    const rootExport = resolveConditionalExport(exportsField['.']);
    return rootExport ?? resolveConditionalExport(exportsField);
}
function resolveEntryFromPackageJson(packageJson) {
    const exportedEntry = resolvePackageRootExport(packageJson.exports);
    if (exportedEntry) {
        return exportedEntry;
    }
    if (typeof packageJson.module === 'string') {
        return packageJson.module;
    }
    if (typeof packageJson.main === 'string') {
        return packageJson.main;
    }
    return 'index.js';
}
/**
 * 主干流程：从 bridge 自身安装根下的 node_modules 读取包元数据，
 * 按 package.json 的 exports/module/main 定位真实 ESM 入口，避免猜测根目录 index.js。
 */
export async function resolveBridgePackageEntryPath(packageName, packageRoot = BRIDGE_PACKAGE_ROOT) {
    const packageDirectory = getPackageDirectory(packageName, packageRoot);
    const packageJsonPath = path.join(packageDirectory, 'package.json');
    const rawPackageJson = await readFile(packageJsonPath, 'utf8');
    const packageJson = JSON.parse(rawPackageJson);
    const entry = resolveEntryFromPackageJson(packageJson);
    const entryPath = path.resolve(packageDirectory, entry);
    await access(entryPath);
    return entryPath;
}
/**
 * 具体实现逻辑：优先从 bridge-local 安装目录显式导入真实入口；
 * 若没有本地 package.json，则退回 Node 的包名解析以兼容开发环境。
 */
export async function importBridgeSdkPackage(packageName) {
    try {
        const entryPath = await resolveBridgePackageEntryPath(packageName);
        return (await import(pathToFileURL(entryPath).href));
    }
    catch (error) {
        if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
            return (await import(packageName));
        }
        throw error;
    }
}
