import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import semver from 'semver';
import * as _ from 'lodash-es';
import { packageJson } from '../../lib/index.mjs';
import { packageNameToNamespace, removeFieldsWithNullishValues } from './support/index.mjs';
import { mergeBlueprints, parseBluePrints, loadBlueprintsFromConfiguration, normalizeBlueprintName } from './internal/index.mjs';
import { PRIORITY_NAMES } from './priorities.mjs';
import CoreGenerator from '../base-core/index.mjs';
import { LOCAL_BLUEPRINT_PACKAGE_NAMESPACE } from './support/constants.mjs';
import { getConfigWithDefaults } from '../../jdl/index.js';
import { loadStoredAppOptions } from '../app/support/index.mjs';
const { defaults } = _;
export default class JHipsterBaseBlueprintGenerator extends CoreGenerator {
    fromBlueprint;
    sbsBlueprint;
    delegateToBlueprint;
    blueprintConfig;
    jhipsterContext;
    constructor(args, options, features) {
        const { jhipsterContext, ...opts } = options ?? {};
        super(args, opts, features);
        if (this.options.help) {
            return;
        }
        loadStoredAppOptions.call(this);
        this.sbsBlueprint = this.features.sbsBlueprint ?? false;
        this.fromBlueprint = this.rootGeneratorName() !== 'generator-begcode';
        if (this.fromBlueprint) {
            this.blueprintStorage = this._getStorage();
            this.blueprintConfig = this.blueprintStorage.createProxy();
            this.jhipsterContext = jhipsterContext;
            if (this.getFeatures().checkBlueprint) {
                if (!this.jhipsterContext) {
                    throw new Error(`This is a JHipster blueprint and should be used only like ${chalk.yellow(`jhipster --blueprints ${this.options.namespace.split(':')[0]}`)}`);
                }
            }
            try {
                const blueprintedTemplatePath = this.jhipsterTemplatePath();
                if (!this.jhipsterTemplatesFolders.includes(blueprintedTemplatePath)) {
                    this.jhipsterTemplatesFolders.push(blueprintedTemplatePath);
                }
            }
            catch (error) {
                this.log.warn('Error adding current blueprint templates as alternative for Begcode templates.');
                this.log.log(error);
            }
        }
    }
    delegateTasksToBlueprint(tasksGetter) {
        return this.delegateToBlueprint ? {} : tasksGetter();
    }
    get initializing() {
        return this.asInitializingTaskGroup(this._initializing());
    }
    _initializing() {
        return {};
    }
    asInitializingTaskGroup(taskGroup) {
        return taskGroup;
    }
    get prompting() {
        return this.asPromptingTaskGroup(this._prompting());
    }
    _prompting() {
        return {};
    }
    asPromptingTaskGroup(taskGroup) {
        return taskGroup;
    }
    get configuring() {
        return this.asConfiguringTaskGroup(this._configuring());
    }
    _configuring() {
        return {};
    }
    asConfiguringTaskGroup(taskGroup) {
        return taskGroup;
    }
    get composing() {
        return this.asComposingTaskGroup(this._composing());
    }
    _composing() {
        return {};
    }
    asComposingTaskGroup(taskGroup) {
        return taskGroup;
    }
    get loading() {
        return this.asLoadingTaskGroup(this._loading());
    }
    _loading() {
        return {};
    }
    asLoadingTaskGroup(taskGroup) {
        return taskGroup;
    }
    get preparing() {
        return this.asPreparingTaskGroup(this._preparing());
    }
    _preparing() {
        return {};
    }
    asPreparingTaskGroup(taskGroup) {
        return taskGroup;
    }
    get postPreparing() {
        return this.asPreparingTaskGroup({});
    }
    asPostPreparingTaskGroup(taskGroup) {
        return taskGroup;
    }
    get default() {
        return this.asDefaultTaskGroup(this._default());
    }
    _default() {
        return {};
    }
    asDefaultTaskGroup(taskGroup) {
        return taskGroup;
    }
    get writing() {
        return this.asWritingTaskGroup(this._writing());
    }
    _writing() {
        return {};
    }
    asWritingTaskGroup(taskGroup) {
        return taskGroup;
    }
    get postWriting() {
        return this.asPostWritingTaskGroup(this._postWriting());
    }
    _postWriting() {
        return {};
    }
    asPostWritingTaskGroup(taskGroup) {
        return taskGroup;
    }
    get install() {
        return this.asInstallTaskGroup(this._install());
    }
    _install() {
        return {};
    }
    asInstallTaskGroup(taskGroup) {
        return taskGroup;
    }
    get postInstall() {
        return this.asPostInstallTaskGroup(this._postInstall());
    }
    _postInstall() {
        return {};
    }
    asPostInstallTaskGroup(taskGroup) {
        return taskGroup;
    }
    get end() {
        return this.asEndTaskGroup(this._end());
    }
    _end() {
        return {};
    }
    asEndTaskGroup(taskGroup) {
        return taskGroup;
    }
    get jhipsterConfigWithDefaults() {
        const configWithDefaults = getConfigWithDefaults(removeFieldsWithNullishValues(this.config.getAll()));
        defaults(configWithDefaults, {
            skipFakeData: false,
            skipCheckLengthOfIdentifier: false,
            enableGradleEnterprise: false,
            pages: [],
        });
        return configWithDefaults;
    }
    async composeWithBlueprints(subGen, options) {
        this.delegateToBlueprint = false;
        const control = this.sharedData.getControl();
        if (!control.blueprintConfigured) {
            control.blueprintConfigured = true;
            await this._configureBlueprints();
        }
        let blueprints = this.jhipsterConfig.blueprints || [];
        if (this.options.composeWithLocalBlueprint) {
            blueprints = blueprints.concat({ name: '@jhipster/local' });
        }
        const composedBlueprints = [];
        for (const blueprint of blueprints) {
            const blueprintGenerator = await this._composeBlueprint(blueprint.name, subGen, options);
            if (blueprintGenerator) {
                composedBlueprints.push(blueprintGenerator);
                if (blueprintGenerator.sbsBlueprint) {
                    this.jhipsterTemplatesFolders.unshift(blueprintGenerator.templatePath());
                }
                else {
                    this.delegateToBlueprint = true;
                    this.checkBlueprintImplementsPriorities(blueprintGenerator);
                }
            }
        }
        return composedBlueprints;
    }
    checkBlueprintImplementsPriorities(blueprintGenerator) {
        const { taskPrefix: baseGeneratorTaskPrefix = '' } = this.features;
        const { taskPrefix: blueprintTaskPrefix = '' } = blueprintGenerator.features;
        const DEPRECATED_PRIORITIES = ['preConflicts'];
        for (const priorityName of Object.values(PRIORITY_NAMES).filter(p => !DEPRECATED_PRIORITIES.includes(p))) {
            const baseGeneratorPriorityName = `${baseGeneratorTaskPrefix}${priorityName}`;
            if (baseGeneratorPriorityName in this) {
                const blueprintPriorityName = `${blueprintTaskPrefix}${priorityName}`;
                if (!Object.hasOwn(Object.getPrototypeOf(blueprintGenerator), blueprintPriorityName)) {
                    this.log.debug(`Priority ${blueprintPriorityName} not implemented at ${blueprintGenerator.options.namespace}.`);
                }
            }
        }
    }
    async _configureBlueprints() {
        let argvBlueprints = this.options.blueprints || '';
        const blueprint = this.options.blueprint;
        if (blueprint) {
            this.log.warn('--blueprint option is deprecated. Please use --blueprints instead');
            if (!argvBlueprints.split(',').includes(blueprint)) {
                argvBlueprints = `${blueprint},${argvBlueprints}`;
            }
        }
        const blueprints = mergeBlueprints(parseBluePrints(argvBlueprints), loadBlueprintsFromConfiguration(this.config));
        const missingBlueprints = blueprints
            .filter(blueprint => !this.env.isPackageRegistered(packageNameToNamespace(blueprint.name)))
            .map(blueprint => blueprint.name);
        if (missingBlueprints.length > 0) {
            await this.env.lookup({ filterPaths: true, packagePatterns: missingBlueprints });
        }
        if (blueprints && blueprints.length > 0) {
            blueprints.forEach(blueprint => {
                blueprint.version = this._findBlueprintVersion(blueprint.name) || blueprint.version;
            });
            this.jhipsterConfig.blueprints = blueprints;
        }
        if (!this.skipChecks) {
            const namespaces = blueprints.map(blueprint => packageNameToNamespace(blueprint.name));
            const missing = namespaces.filter(namespace => !this.env.isPackageRegistered(namespace));
            if (missing && missing.length > 0) {
                throw new Error(`Some blueprints were not found ${missing}, you should install them manually`);
            }
        }
    }
    async _composeBlueprint(blueprint, subGen, extraOptions = {}) {
        blueprint = normalizeBlueprintName(blueprint);
        if (!this.skipChecks && blueprint !== LOCAL_BLUEPRINT_PACKAGE_NAMESPACE) {
            this._checkBlueprint(blueprint);
        }
        const generatorName = packageNameToNamespace(blueprint);
        const generatorNamespace = `${generatorName}:${subGen}`;
        if (!this.env.isPackageRegistered(generatorName)) {
            await this.env.lookup({ filterPaths: true, packagePatterns: blueprint });
        }
        if (!(await this.env.get(generatorNamespace))) {
            this.log.debug(`No blueprint found for blueprint ${chalk.yellow(blueprint)} and ${chalk.yellow(subGen)} with namespace ${chalk.yellow(generatorNamespace)} subgenerator: falling back to default generator`);
            return undefined;
        }
        this.log.debug(`Found blueprint ${chalk.yellow(blueprint)} and ${chalk.yellow(subGen)} with namespace ${chalk.yellow(generatorNamespace)}`);
        const finalOptions = {
            forwardOptions: true,
            ...extraOptions,
            generatorOptions: {
                jhipsterContext: this,
                ...extraOptions?.generatorOptions,
            },
        };
        const blueprintGenerator = await this.composeWith(generatorNamespace, finalOptions);
        if (blueprintGenerator instanceof Error) {
            throw blueprintGenerator;
        }
        this._debug(`Using blueprint ${chalk.yellow(blueprint)} for ${chalk.yellow(subGen)} subgenerator`);
        return blueprintGenerator;
    }
    _findBlueprintPackageJson(blueprintPkgName) {
        const blueprintGeneratorName = packageNameToNamespace(blueprintPkgName);
        const blueprintPackagePath = this.env.getPackagePath(blueprintGeneratorName);
        if (!blueprintPackagePath) {
            this.log.warn(`Could not retrieve packagePath of blueprint '${blueprintPkgName}'`);
            return undefined;
        }
        const packageJsonFile = path.join(blueprintPackagePath, 'package.json');
        if (!fs.existsSync(packageJsonFile)) {
            return undefined;
        }
        return JSON.parse(fs.readFileSync(packageJsonFile).toString());
    }
    _findBlueprintVersion(blueprintPkgName) {
        const blueprintPackageJson = this._findBlueprintPackageJson(blueprintPkgName);
        if (!blueprintPackageJson || !blueprintPackageJson.version) {
            this.log.warn(`Could not retrieve version of blueprint '${blueprintPkgName}'`);
            return undefined;
        }
        return blueprintPackageJson.version;
    }
    _checkBlueprint(blueprint) {
        if (blueprint === 'generator-begcode') {
            throw new Error(`You cannot use ${chalk.yellow(blueprint)} as the blueprint.`);
        }
        this._findBlueprintPackageJson(blueprint);
    }
    _checkJHipsterBlueprintVersion(blueprintPkgName) {
        const blueprintPackageJson = this._findBlueprintPackageJson(blueprintPkgName);
        if (!blueprintPackageJson) {
            this.log.warn(`Could not retrieve version of JHipster declared by blueprint '${blueprintPkgName}'`);
            return;
        }
        const mainGeneratorJhipsterVersion = packageJson.version;
        const blueprintJhipsterVersion = blueprintPackageJson.dependencies && blueprintPackageJson.dependencies['generator-begcode'];
        if (blueprintJhipsterVersion) {
            if (!semver.valid(blueprintJhipsterVersion) && !semver.validRange(blueprintJhipsterVersion)) {
                this.log.verboseInfo(`Blueprint ${blueprintPkgName} contains generator-begcode dependency with non comparable version`);
                return;
            }
            if (semver.satisfies(mainGeneratorJhipsterVersion, blueprintJhipsterVersion, { includePrerelease: true })) {
                return;
            }
            throw new Error(`The installed ${chalk.yellow(blueprintPkgName)} blueprint targets JHipster v${blueprintJhipsterVersion} and is not compatible with this JHipster version. Either update the blueprint or JHipster. You can also disable this check using --skip-checks at your own risk`);
        }
        const blueprintPeerJhipsterVersion = blueprintPackageJson.peerDependencies && blueprintPackageJson.peerDependencies['generator-begcode'];
        if (blueprintPeerJhipsterVersion) {
            if (semver.satisfies(mainGeneratorJhipsterVersion, blueprintPeerJhipsterVersion, { includePrerelease: true })) {
                return;
            }
            throw new Error(`The installed ${chalk.yellow(blueprintPkgName)} blueprint targets JHipster ${blueprintPeerJhipsterVersion} and is not compatible with this JHipster version. Either update the blueprint or JHipster. You can also disable this check using --skip-checks at your own risk`);
        }
        this.log.warn(`Could not retrieve version of JHipster declared by blueprint '${blueprintPkgName}'`);
    }
}
