"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.discoverTypedocPlugins = discoverTypedocPlugins;
exports.buildTypedocPluginsCode = buildTypedocPluginsCode;
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const path = tslib_1.__importStar(require("path"));
/**
 * Non-local scopes whose packages should be documented.
 * Packages under 'local' are internal-only and excluded.
 */
const DOCUMENTED_SCOPES = [
    'kaltura-corp',
    'kaltura-apps',
    'kaltura-ui',
    'kaltura-sdk',
    'unisphere',
];
/**
 * Returns the npm package name for a given sourceRoot by looking up
 * tsconfig.base.json paths.
 * e.g. sourceRoot "unisphere/packages/kaltura-corp/shared-react"
 *   → "@kaltura-corp/unisphere-genie-shared-react"
 */
function findPackageName(tree, sourceRoot) {
    if (!tree.exists('tsconfig.base.json'))
        return null;
    try {
        const tsconfig = (0, devkit_1.readJson)(tree, 'tsconfig.base.json');
        const paths = tsconfig?.compilerOptions?.paths ?? {};
        const expectedPath = `${sourceRoot}/src/index.ts`;
        for (const [alias, pathList] of Object.entries(paths)) {
            if (Array.isArray(pathList) && pathList.includes(expectedPath)) {
                return alias;
            }
        }
    }
    catch {
        // ignore
    }
    return null;
}
/**
 * Derives a short plugin id from an npm package name.
 * "@kaltura-corp/unisphere-genie-shared-react" → "unisphere-genie-shared-react"
 * "@unisphere/genie-types" → "genie-types"
 */
function shortName(packageName) {
    const parts = packageName.split('/');
    return parts[parts.length - 1];
}
/**
 * Discovers publishable packages from .unisphere config and generates
 * docusaurus-plugin-typedoc configuration entries.
 *
 * Excludes packages whose sourceRoot contains '/local/' (internal packages).
 * The docsProjectRoot is used to compute relative paths (e.g. "unisphere/documentation/genie").
 */
function discoverTypedocPlugins(tree, docsProjectRoot) {
    if (!tree.exists('.unisphere'))
        return [];
    let config;
    try {
        config = (0, devkit_1.readJson)(tree, '.unisphere');
    }
    catch {
        return [];
    }
    const packages = config?.elements?.packages ?? {};
    const plugins = [];
    for (const [, pkgConfig] of Object.entries(packages)) {
        const sourceRoot = pkgConfig?.sourceRoot;
        if (!sourceRoot)
            continue;
        // Determine the scope directory from the sourceRoot path
        // Expected: unisphere/packages/<scope>/<name>
        const parts = sourceRoot.split('/');
        if (parts.length < 4)
            continue;
        const scope = parts[2]; // e.g. "local", "kaltura-corp", "unisphere"
        if (!DOCUMENTED_SCOPES.includes(scope))
            continue;
        const packageName = findPackageName(tree, sourceRoot);
        if (!packageName) {
            devkit_1.logger.warn(`⚠️  Could not find npm package name for ${sourceRoot} — skipping in typedoc plugins`);
            continue;
        }
        const short = shortName(packageName);
        // Relative path from docs site root to the package
        // docsProjectRoot: "unisphere/documentation/genie"
        // sourceRoot:       "unisphere/packages/kaltura-corp/shared-react"
        const relativeBase = path.relative(docsProjectRoot, sourceRoot).replace(/\\/g, '/');
        plugins.push({
            id: `api-${short}`,
            packageName,
            entryPointsRelative: `${relativeBase}/src/index.ts`,
            tsconfigRelative: `${relativeBase}/tsconfig.json`,
            out: `docs/api/${short}/v1`,
        });
    }
    return plugins;
}
/**
 * Serialises the discovered plugin configs into a TypeScript source fragment
 * suitable for injection into docusaurus.config.ts via EJS (<%- typedocPluginsConfig %>).
 */
function buildTypedocPluginsCode(plugins) {
    if (plugins.length === 0)
        return '[]';
    const entries = plugins
        .map((p) => `\n    // ${p.packageName}\n` +
        `    [\n` +
        `      'docusaurus-plugin-typedoc',\n` +
        `      {\n` +
        `        id: '${p.id}',\n` +
        `        entryPoints: ['${p.entryPointsRelative}'],\n` +
        `        tsconfig: '${p.tsconfigRelative}',\n` +
        `        out: '${p.out}',\n` +
        `        readme: 'none',\n` +
        `        excludePrivate: true,\n` +
        `        excludeProtected: true,\n` +
        `        excludeInternal: true,\n` +
        `        disableSources: true,\n` +
        `      },\n` +
        `    ]`)
        .join(',');
    return `[${entries},\n  ]`;
}
