import { config, Helpers__NS__createSymLink, Helpers__NS__error, Helpers__NS__exists, Helpers__NS__info, Helpers__NS__isSymlinkFileExitedOrUnexisted, Helpers__NS__isUnexistedLink, Helpers__NS__log, Helpers__NS__logWarn, Helpers__NS__questionYesNo, Helpers__NS__readJsonC, Helpers__NS__remove, Helpers__NS__removeIfExists, Helpers__NS__removeSymlinks, Helpers__NS__run, Helpers__NS__taskDone, Helpers__NS__taskStarted, Helpers__NS__warn } from 'tnp-core/lib-prod';
import { crossPlatformPath, fse, path, dateformat, ___NS__cloneDeep, ___NS__first, ___NS__isUndefined } from 'tnp-core/lib-prod';
import { UtilsFilesFoldersSync__NS__getFoldersFrom } from 'tnp-core/lib-prod';
import { HelpersTaon__NS__consoleGui__NS__select, HelpersTaon__NS__copy } from '../../index';
export class BaseNodeModules {
    cwd;
    npmHelpers;
    _npmHelpersType;
    //#region constructor
    constructor(
    /**
     * my-path/node_modules
     */
    cwd, npmHelpers) {
        this.cwd = cwd;
        this.npmHelpers = npmHelpers;
        this.npmHelpers = npmHelpers;
    }
    //#endregion
    //#region path
    /**
     * cwd + node_modules
     */
    get path() {
        return crossPlatformPath([this.cwd, config.folder.node_modules]);
    }
    //#endregion
    //#region path for package
    /**
     * Path to package inside node_modules folder
     * @example <project-path>/node_modules/<package-name>
     */
    pathFor(packageName) {
        //#region @backendFunc
        packageName = crossPlatformPath(packageName);
        return crossPlatformPath([this.realPath, packageName]);
        //#endregion
    }
    //#endregion
    //#region real path of node_modules - if node_modules is a link
    /**
     * real path of node_modules
     * if node_modules is a link
     * it will return real path.
     * if node_modules is folder = path
     */
    get realPath() {
        try {
            const realPath = crossPlatformPath(fse.realpathSync(this.path));
            return realPath;
        }
        catch (error) {
            return this.path;
        }
    }
    //#endregion
    //#region prevent wrong link destination
    preventWrongLinkDestination(dest) {
        if (!path.isAbsolute(dest)) {
            Helpers__NS__error(`[linkTo..] target destination path is not absolute "${dest}"`);
        }
        if (dest.endsWith(`/${config.folder.node_modules}`)) {
            return dest;
        }
        return crossPlatformPath([dest, config.folder.node_modules]);
    }
    //#endregion
    //#region link node_modules to other project
    linkToProject(project) {
        //#region @backendFunc
        const source = this.realPath;
        let dest = project.pathFor(config.folder.node_modules);
        dest = this.preventWrongLinkDestination(dest);
        Helpers__NS__createSymLink(source, dest, {
            continueWhenExistedFolderDoesntExists: true,
        });
        //#endregion
    }
    //#endregion
    //#region link node_modules to other project
    copyToProject(project) {
        //#region @backendFunc
        Helpers__NS__taskStarted(`Copying node_modules folder to project ${project.name}/node_modules`);
        const source = this.realPath;
        let dest = project.pathFor(config.folder.node_modules);
        dest = this.preventWrongLinkDestination(dest);
        Helpers__NS__removeSymlinks(dest);
        Helpers__NS__remove(dest, true);
        HelpersTaon__NS__copy(source, dest, {
            recursive: true,
            overwrite: true,
            copySymlinksAsFiles: false,
        });
        Helpers__NS__taskDone(`Done copying node_modules folder to project ${project.name}/node_modules`);
        //#endregion
    }
    //#endregion
    //#region link to project or location
    linkToLocation(location) {
        //#region @backendFunc
        let dest = crossPlatformPath(location);
        dest = this.preventWrongLinkDestination(dest);
        Helpers__NS__remove(dest, true);
        Helpers__NS__createSymLink(this.realPath, dest, {
            continueWhenExistedFolderDoesntExists: true,
        });
        //#endregion
    }
    //#endregion
    //#region make sure node modules installed
    async makeSureInstalled(options) {
        if (this.isEmpty()) {
            await this.reinstall(options);
        }
    }
    //#endregion
    //#region delete node_modules
    async remove(options) {
        //#region @backendFunc
        options = options || {};
        if (options.skipQuestion ||
            (await Helpers__NS__questionYesNo(`You are about delete ${config.folder.node_modules} (Yes -> continue, No -> skip action) ?`))) {
            Helpers__NS__removeSymlinks(this.path);
            Helpers__NS__remove(this.path, true);
        }
        //#endregion
    }
    //#endregion
    //#region remove package inside
    removePackage(packageInside) {
        //#region @backendFunc
        Helpers__NS__log(`Removing node_modules from ${this.path}`);
        Helpers__NS__removeIfExists([this.path, packageInside]);
        //#endregion
    }
    //#endregion
    //#region reinstall node modules
    async reinstall(options) {
        //#region @backendFunc
        options = ___NS__cloneDeep(options || {});
        if (___NS__isUndefined(options.useYarn)) {
            options.useYarn = this.npmHelpers.preferYarnOverNpm();
        }
        if (___NS__isUndefined(options.removeYarnOrPackageJsonLock)) {
            options.removeYarnOrPackageJsonLock = true;
        }
        Helpers__NS__taskStarted(`
      [${dateformat(new Date(), 'dd-mm-yyyy HH:MM:ss')}]
      Reinstalling node modules in:
${this.cwd}

with ${options.useYarn ? 'yarn' : 'npm'}

      `);
        while (true) {
            if (!options.skipRemovingNodeModules) {
                await this.remove({ skipQuestion: true });
            }
            // TODO @LAST - use method makeSureNodeModulesInstalled()
            try {
                Helpers__NS__run(await this.prepareCommand(options, this.cwd), {
                    output: true,
                    silence: false,
                    cwd: this.cwd,
                }).sync();
                break;
            }
            catch (error) {
                console.log(error);
                const nodeModulesInstallFailOptions = {
                    again: {
                        name: 'Try again normal installation',
                    },
                    againForce: {
                        name: 'Try again force installation',
                    },
                    skip: {
                        name: 'Skip this error and continue',
                    },
                    exit: {
                        name: 'Exit process',
                    },
                };
                const res = await HelpersTaon__NS__consoleGui__NS__select('What to do?', nodeModulesInstallFailOptions);
                if (res === 'again') {
                    options.force = false;
                    continue;
                }
                if (res === 'againForce') {
                    options.force = true;
                    continue;
                }
                if (res === 'exit') {
                    process.exit(0);
                }
                if (res === 'skip') {
                    break;
                }
            }
        }
        Helpers__NS__taskDone(`
      [${dateformat(new Date(), 'dd-mm-yyyy HH:MM:ss')}]
      Reinstalled node modules for ${this.cwd}
      `);
        this.npmHelpers.packageJson.reloadPackageJsonInMemory();
        //#endregion
    }
    //#endregion
    //#region is link
    get isLink() {
        return Helpers__NS__isSymlinkFileExitedOrUnexisted(this.path);
    }
    //#endregion
    unlinkNodeModulesWhenLinked() {
        //#region @backendFunc
        if (this.isLink) {
            try {
                Helpers__NS__info(`Unlinking incorrect node_modules link from ${path.basename(this.cwd)}`);
                fse.unlinkSync(this.path);
            }
            catch (error) { }
        }
        //#endregion
    }
    //#region empty
    get empty() {
        return this.isEmpty();
    }
    //#endregion
    //#region fields & getters / empty node_modules
    /**
     * @returns true if node_modules folder is empty
     * DEEP CHECK - also if node_modules is a link
     * and is not existent
     */
    isEmpty() {
        //#region @backendFunc
        let node_modules_path = this.path;
        if (Helpers__NS__isUnexistedLink(node_modules_path)) {
            try {
                Helpers__NS__logWarn(`[npm-helpers][emptyNodeModules] removing unexisted node_modules` +
                    ` link form ${this.cwd}`);
                fse.unlinkSync(node_modules_path);
            }
            catch (error) { }
            return true;
        }
        if (Helpers__NS__exists(node_modules_path)) {
            try {
                const real_node_modules_path = crossPlatformPath(fse.realpathSync(crossPlatformPath([this.cwd, config.folder.node_modules])));
                node_modules_path = real_node_modules_path;
            }
            catch (error) { }
        }
        if (!Helpers__NS__exists(node_modules_path)) {
            return true;
        }
        if (!Helpers__NS__exists(crossPlatformPath([node_modules_path, '.bin']))) {
            return true;
        }
        const childrenInNodeModules = UtilsFilesFoldersSync__NS__getFoldersFrom(node_modules_path, {
            followSymlinks: false,
            recursive: false,
        });
        if (childrenInNodeModules.length === 0) {
            return true;
        }
        if (childrenInNodeModules.length === 1) {
            Helpers__NS__logWarn(`[npm-helpers] Only ` +
                `${path.basename(___NS__first(childrenInNodeModules))} folder in node_modules in ${this.cwd}`);
            return true;
        }
        const minDepsLength = Object.keys(this.npmHelpers.packageJson.allDependencies).length;
        const notFullyInstalled = childrenInNodeModules.length < minDepsLength + 1;
        if (notFullyInstalled) {
            Helpers__NS__logWarn(`[npm-helpers] Not all deps are installed in ${this.cwd}`);
        }
        return notFullyInstalled;
        //#endregion
    }
    //#endregion
    //#region prepare command
    /**
     *  Prepare command for npm install
     * (or yarn install)
     */
    async prepareCommand(options, cwd = this.cwd) {
        //#region @backendFunc
        let { pkg, silent, useYarn, force, removeYarnOrPackageJsonLock, generateYarnOrPackageJsonLock, } = options || {};
        force = true; // TODO QUICK_FIX @UNCOMMENT
        let command = '';
        const commonOptions = `--ignore-engines`;
        if (useYarn) {
            //#region yarn
            const argsForFasterInstall = `${force ? '--force' : ''} ${commonOptions} `;
            if (removeYarnOrPackageJsonLock) {
                const yarnLock = crossPlatformPath([cwd, config.file.yarn_lock]);
                try {
                    fse.unlinkSync(yarnLock);
                }
                catch (error) { }
                fse.writeFileSync(yarnLock, ''); // simulate touch
            }
            command =
                `yarn ${pkg ? (pkg?.installType === 'remove' ? 'remove' : 'add') : 'install'} ${pkg ? pkg.name : ''} ` +
                    ` ${generateYarnOrPackageJsonLock ? '' : '--no-lockfile'} ` +
                    ` ${argsForFasterInstall} ` +
                    ` ${pkg && pkg.installType && pkg.installType === '--save-dev' ? '-dev' : ''} `;
            //#endregion
        }
        else {
            //#region npm
            const argsForFasterInstall = `${force ? '--force' : ''} ${commonOptions} --no-audit ` +
                `${silent ? '--silent --no-progress' : ''}   `;
            if (removeYarnOrPackageJsonLock) {
                const packageLock = crossPlatformPath([
                    cwd,
                    config.file.package_lock_json,
                ]);
                try {
                    fse.unlinkSync(packageLock);
                }
                catch (error) { }
                fse.writeFileSync(packageLock, ''); // simulate touch
            }
            command =
                `npx --node-options=--max-old-space-size=8000 npm ` +
                    `${pkg?.installType === 'remove' ? 'uninstall' : 'install'} ${pkg ? pkg.name : ''} ` +
                    ` ${generateYarnOrPackageJsonLock ? '' : '--no-package-lock'} ` +
                    ` ${pkg && pkg.installType ? pkg.installType : ''} ` +
                    ` ${argsForFasterInstall} `;
            //#endregion
        }
        Helpers__NS__info(`Command for npm install:

      ${command}

      `);
        return command;
        //#endregion
    }
    //#endregion
    //#region find package dirs
    /**
     *
     * @param rootDir
     * @param packageName
     * @returns absolute paths to package dirs
     */
    findPackageDirs(rootDir, packageName, options = {}) {
        //#region @backendFunc
        const results = [];
        const visited = new Set();
        const maxDepth = options.maxDepth ?? 10;
        const targetParts = packageName.split('/'); // handle @scope/pkg
        const walk = (dir, depth = 0) => {
            if (options.signal?.aborted)
                return;
            if (depth > maxDepth)
                return;
            if (visited.has(dir))
                return;
            visited.add(dir);
            let entries;
            try {
                entries = fse.readdirSync(dir, { withFileTypes: true });
            }
            catch {
                return; // permission or broken symlink
            }
            for (const entry of entries) {
                if (!entry.isDirectory())
                    continue;
                const subdir = crossPlatformPath([dir, entry.name]);
                // we only care about node_modules structure
                if (entry.name === 'node_modules' || dir.endsWith('node_modules')) {
                    // try to match direct package or @scope/pkg structure
                    if (entry.name === targetParts[0] && targetParts.length === 1) {
                        results.push(subdir);
                        continue;
                    }
                    if (entry.name === targetParts[0] && targetParts.length > 1) {
                        const scoped = crossPlatformPath([subdir, targetParts[1]]);
                        try {
                            const stat = fse.statSync(scoped);
                            if (stat.isDirectory())
                                results.push(scoped);
                        }
                        catch { }
                        continue;
                    }
                    // otherwise keep descending only within node_modules
                    walk(subdir, depth + 1);
                }
            }
        };
        walk(rootDir);
        return results;
        //#endregion
    }
    //#endregion
    //#region dedupe packages action
    dedupePackages(packagesConfig, countOnly = false, fake = false) {
        //#region @backendFunc
        // packagesConfig = ['@angular/cdk', 'tnp-models'];
        Helpers__NS__taskStarted(`${countOnly ? 'Counting' : 'Removing'} duplicates in node_modules ${fake ? '(fake process)' : ''}...`);
        for (const entry of packagesConfig) {
            let packageNameForDuplicationRemoval;
            let excludeFrom = [];
            let includeOnlyIn = [];
            if (typeof entry === 'string') {
                packageNameForDuplicationRemoval = entry;
            }
            else {
                packageNameForDuplicationRemoval = entry.package;
                excludeFrom = entry.excludeFrom || [];
                includeOnlyIn = entry.includeOnlyIn || [];
            }
            packageNameForDuplicationRemoval = crossPlatformPath(packageNameForDuplicationRemoval);
            Helpers__NS__info(`[${config.frameworkName}] Checking npm duplicates of ${packageNameForDuplicationRemoval}`);
            const nodeModulesRoot = crossPlatformPath([
                this.cwd,
                config.folder.node_modules,
            ]);
            Helpers__NS__taskStarted(`Looking for directories ${packageNameForDuplicationRemoval}`);
            const foundAbsPaths = this.findPackageDirs(nodeModulesRoot, packageNameForDuplicationRemoval, { maxDepth: 15 });
            Helpers__NS__log(foundAbsPaths);
            // console.log({foundAbsPaths})
            Helpers__NS__taskDone(`Looking for directories done. Found: ${foundAbsPaths.length}`);
            const duplicates = foundAbsPaths.filter(foundedAbsPath => {
                // console.log({ foundedRelativePath });
                const relative = crossPlatformPath([
                    foundedAbsPath.replace(nodeModulesRoot + '/', ''),
                ]);
                // console.log({ relative });
                if (relative?.startsWith('..')) {
                    return false;
                }
                let root = ___NS__first(relative.split('/'));
                if (root?.startsWith('@')) {
                    root = root + '/' + relative.split('/')[1];
                }
                root = root || '';
                const packageJsonAbsPath = crossPlatformPath([
                    this.cwd,
                    config.folder.node_modules,
                    relative,
                    'package.json',
                ]);
                const packageJsonExtractedName = Helpers__NS__readJsonC(packageJsonAbsPath)?.name;
                return (packageJsonExtractedName === packageNameForDuplicationRemoval &&
                    root !== packageNameForDuplicationRemoval &&
                    ___NS__first(root.split('/')) !== config.folder._bin &&
                    fse.existsSync(packageJsonAbsPath));
            });
            // console.log({ duplicates });
            duplicates.forEach(duplicatePathAbs => {
                const pathParts = duplicatePathAbs.split('/').filter(Boolean);
                const nodeModulesIndex = pathParts.lastIndexOf('node_modules');
                let parentName;
                if (pathParts[nodeModulesIndex - 2]?.startsWith('@')) {
                    parentName = pathParts[nodeModulesIndex - 2];
                }
                else {
                    parentName = pathParts[nodeModulesIndex - 1];
                }
                if (!Helpers__NS__exists(duplicatePathAbs)) {
                    Helpers__NS__warn(`Skipping non-existing path: ${duplicatePathAbs}`);
                    return;
                }
                if (excludeFrom.some(rule => parentName.includes(rule.replace('!', '')))) {
                    Helpers__NS__warn(`Skipping removal of ${packageNameForDuplicationRemoval} from excluded parent: ${parentName}`);
                    return;
                }
                if (includeOnlyIn.length > 0 &&
                    !includeOnlyIn.some(rule => parentName.includes(rule.replace('*', '')))) {
                    Helpers__NS__warn(`Skipping removal of ${packageNameForDuplicationRemoval} from non-included parent: ${parentName}`);
                    return;
                }
                if (countOnly) {
                    Helpers__NS__info(`Found duplicate ${packageNameForDuplicationRemoval}`);
                }
                else {
                    Helpers__NS__info(`Removing path ${duplicatePathAbs}`);
                    if (!fake) {
                        Helpers__NS__removeSymlinks(duplicatePathAbs);
                        Helpers__NS__remove(duplicatePathAbs);
                    }
                    // Helpers__NS__info(
                    //   `Removed duplicate ${packageNameForDuplicationRemoval} `,
                    // );
                }
            });
        }
        Helpers__NS__taskDone(`${countOnly ? 'Counting' : 'Removing'} duplicates done.`);
        //#endregion
    }
}
//# sourceMappingURL=c:/Users/darek/projects/npm/taon-dev/tnp-helpers/dist-nocutsrc-prod/lib/base/classes/base-node-modules.js.map