#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAppFromTemplate = createAppFromTemplate;
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const common_1 = require("./common");
const PACKAGE_NAME_PATTERN = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
function createAppFromTemplate(args = process.argv.slice(2)) {
    if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
        printUsage();
        return args.length === 0 ? 1 : 0;
    }
    const packageName = args[0];
    if (!PACKAGE_NAME_PATTERN.test(packageName)) {
        console.error(`Error: Invalid package name: ${packageName}`);
        return 1;
    }
    const unscopedName = packageName.includes('/') ? packageName.split('/').pop() : packageName;
    const targetDir = args[1] || unscopedName;
    const absoluteTarget = (0, node_path_1.resolve)(targetDir);
    if ((0, node_fs_1.existsSync)(absoluteTarget)) {
        console.error(`Error: Directory already exists: ${absoluteTarget}`);
        return 1;
    }
    const packageRoot = (0, common_1.findPackageRoot)();
    const templateDir = (0, node_path_1.join)(packageRoot, 'template-app');
    if (!(0, node_fs_1.existsSync)(templateDir)) {
        console.error('Error: Template directory not found. Ensure @zyno-io/ts-server-foundation is properly installed.');
        return 1;
    }
    const version = getFoundationVersion(packageRoot);
    const replacements = {
        '%%PACKAGE_NAME%%': packageName,
        '%%APP_DB_NAME%%': unscopedName.replace(/[^a-z0-9]/g, '_'),
        '%%APP_REDIS_PREFIX%%': unscopedName.replace(/[-_.]/g, ''),
        '%%FOUNDATION_VERSION%%': version,
        '%%TSF_VERSION%%': version,
        '%%TTSC_VERSION%%': (0, common_1.readPackageDependencyVersion)(packageRoot, 'ttsc'),
        '%%TYPESCRIPT_VERSION%%': (0, common_1.readPackageDependencyVersion)(packageRoot, 'typescript')
    };
    console.log(`Creating ${packageName} in ${absoluteTarget}...`);
    copyTemplate(templateDir, absoluteTarget, replacements);
    console.log();
    console.log('Done. Next steps:');
    console.log(`  cd ${targetDir}`);
    console.log('  corepack yarn install');
    console.log('  corepack yarn dev');
    return 0;
}
function printUsage() {
    console.log('Usage: tsf-create-app <package-name> [path]');
    console.log();
    console.log('Arguments:');
    console.log('  <package-name>  npm package name, for example @myorg/my-api or my-api');
    console.log('  [path]          Output directory, defaulting to the unscoped package name');
}
function getFoundationVersion(packageRoot) {
    try {
        const pkg = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(packageRoot, 'package.json'), 'utf8'));
        if (!pkg.version || pkg.version === '0.0.0-dev')
            return '*';
        return `^${pkg.version}`;
    }
    catch {
        return '*';
    }
}
function copyTemplate(src, dest, replacements) {
    (0, node_fs_1.mkdirSync)(dest, { recursive: true });
    for (const entry of (0, node_fs_1.readdirSync)(src, { withFileTypes: true })) {
        const srcPath = (0, node_path_1.join)(src, entry.name);
        const destName = entry.name === 'gitignore.tmpl' ? '.gitignore' : entry.name.endsWith('.tmpl') ? entry.name.slice(0, -5) : entry.name;
        const destPath = (0, node_path_1.join)(dest, destName);
        if (entry.isDirectory()) {
            copyTemplate(srcPath, destPath, replacements);
            continue;
        }
        let content = (0, node_fs_1.readFileSync)(srcPath, 'utf8');
        for (const [key, value] of Object.entries(replacements)) {
            content = content.split(key).join(value);
        }
        (0, node_fs_1.writeFileSync)(destPath, content);
    }
}
if (require.main === module) {
    process.exit(createAppFromTemplate());
}
//# sourceMappingURL=tsf-create-app.js.map