"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = update;
const devkit_1 = require("@nx/devkit");
const fs_1 = require("fs");
const path_1 = require("path");
async function update(tree) {
    devkit_1.logger.info('🔄 Replacing README.md from template...');
    const readmePath = 'README.md';
    const readmeTemplatePath = (0, path_1.join)(__dirname, 'templates', 'readme.md.template');
    const unispherePath = '.unisphere';
    // Read the template content
    const readmeTemplateContent = (0, fs_1.readFileSync)(readmeTemplatePath, 'utf-8');
    // Read and parse .unisphere file
    let processedContent = readmeTemplateContent;
    if (tree.exists(unispherePath)) {
        try {
            const unisphereConfig = (0, devkit_1.readJson)(tree, unispherePath);
            if (!unisphereConfig) {
                throw new Error('.unisphere file is empty');
            }
            // Replace placeholders with values from .unisphere
            if (unisphereConfig.company) {
                processedContent = processedContent.replace(/\{\{company-name\|human-readable\}\}/g, unisphereConfig.company);
            }
            if (unisphereConfig.name) {
                processedContent = processedContent.replace(/\{\{project-name\|human-readable\}\}/g, unisphereConfig.name);
            }
            devkit_1.logger.info(` Replaced template placeholders with company: "${unisphereConfig.company}", name: "${unisphereConfig.name}"`);
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Unknown error';
            devkit_1.logger.warn(` Could not parse .unisphere file: ${errorMessage}`);
            devkit_1.logger.info(' Using template content without placeholder replacement');
        }
    }
    else {
        devkit_1.logger.warn(' .unisphere file not found');
        devkit_1.logger.info(' Using template content without placeholder replacement');
    }
    const readmeExists = tree.exists(readmePath);
    tree.write(readmePath, processedContent);
    if (readmeExists) {
        devkit_1.logger.info(`✅ Updated ${readmePath}`);
    }
    else {
        devkit_1.logger.info(`✅ Created ${readmePath}`);
    }
}
