import { Logger } from '../../config/logger.js';
import { ErrorFactory } from '../../exceptions/ZintrustError.js';
import fs from '../../node-singletons/fs.js';
import * as path from '../../node-singletons/path.js';
const readRootPackageJson = (rootPath) => {
    const rootPackageJsonPath = path.join(rootPath, 'package.json');
    if (!fs.existsSync(rootPackageJsonPath)) {
        throw ErrorFactory.createConfigError(`Missing package.json at: ${rootPackageJsonPath}`);
    }
    try {
        const raw = fs.readFileSync(rootPackageJsonPath, 'utf8');
        return JSON.parse(raw);
    }
    catch (error) {
        throw ErrorFactory.createTryCatchError('Failed to read root package.json', error);
    }
};
const coerceDependencies = (value) => {
    if (typeof value !== 'object' || value === null)
        return {};
    return value;
};
const buildDistPackageJson = (rootPkg) => {
    const name = typeof rootPkg.name === 'string' && rootPkg.name.trim() !== ''
        ? rootPkg.name
        : '@zintrust/core';
    const version = typeof rootPkg.version === 'string' && rootPkg.version.trim() !== ''
        ? rootPkg.version
        : '0.0.0';
    return {
        name,
        version,
        type: 'module',
        main: './index.js',
        types: './index.d.ts',
        bin: {
            zintrust: './bin/zintrust.js',
            zin: './bin/zin.js',
            z: './bin/z.js',
            zt: './bin/zt.js',
        },
        exports: {
            '.': {
                types: './index.d.ts',
                default: './index.js',
            },
            './start': {
                types: './start.d.ts',
                default: './start.js',
            },
            './cli': {
                types: './src/cli.d.ts',
                default: './src/cli.js',
            },
            './proxy': {
                types: './src/proxy.d.ts',
                default: './src/proxy.js',
            },
            './proxy/*': {
                types: './src/proxy/*.d.ts',
                default: './src/proxy/*.js',
            },
            './collections': {
                types: './src/collections/index.d.ts',
                default: './src/collections/index.js',
            },
            './helper': {
                types: './src/helper/index.d.ts',
                default: './src/helper/index.js',
            },
            './node': {
                types: './src/node.d.ts',
                default: './src/node.js',
            },
            './routes/*': {
                types: './routes/*.d.ts',
                default: './routes/*.js',
            },
            './package.json': './package.json',
        },
        dependencies: coerceDependencies(rootPkg.dependencies),
        publishConfig: {
            access: 'public',
        },
    };
};
const writeDistEntrypoints = (distPath) => {
    const distIndexJsPath = path.join(distPath, 'index.js');
    const distIndexDtsPath = path.join(distPath, 'index.d.ts');
    const distStartJsPath = path.join(distPath, 'start.js');
    const distStartDtsPath = path.join(distPath, 'start.d.ts');
    fs.writeFileSync(distIndexJsPath, "export * from './src/index.js';\n");
    fs.writeFileSync(distIndexDtsPath, "export * from './src/index';\n");
    fs.writeFileSync(distStartJsPath, "export * from './src/start.js'; export { default } from './src/start.js';\n");
    fs.writeFileSync(distStartDtsPath, "export * from './src/start'; export { default } from './src/start';\n");
};
const writeDistPackageJson = (distPath, pkg) => {
    const distPackageJsonPath = path.join(distPath, 'package.json');
    fs.writeFileSync(distPackageJsonPath, JSON.stringify(pkg, null, 2) + '\n');
};
const warnIfMissingDistArtifacts = (distPath) => {
    const expected = [
        path.join(distPath, 'src', 'index.js'),
        path.join(distPath, 'bin', 'zintrust.js'),
        path.join(distPath, 'bin', 'zin.js'),
    ];
    for (const candidate of expected) {
        if (!fs.existsSync(candidate)) {
            Logger.warn(`Dist artifact missing (did you run build?): ${candidate}`);
        }
    }
    const docsRoot = path.join(distPath, 'public');
    if (!fs.existsSync(docsRoot)) {
        Logger.warn(`Docs public root missing at ${docsRoot} (expected dist/public)`);
    }
};
export const DistPackager = Object.freeze({
    /**
    * Creates minimal metadata so `dist/` can be installed via `file:/.../dist`
    * without clobbering the publishable package manifest.
     */
    prepare(distPath, rootPath = process.cwd()) {
        if (!fs.existsSync(distPath)) {
            throw ErrorFactory.createConfigError(`Missing dist output at: ${distPath}. Run 'npm run build' first.`);
        }
        const rootPkg = readRootPackageJson(rootPath);
        const distPkg = buildDistPackageJson(rootPkg);
        writeDistPackageJson(distPath, distPkg);
        writeDistEntrypoints(distPath);
        warnIfMissingDistArtifacts(distPath);
        Logger.info(`✅ Prepared dist package metadata at: ${path.join(distPath, 'package.json')}`);
    },
});
