import { dirname, join, relative } from 'path';
import { passthrough } from 'p-transform';
import { loadFile } from 'mem-fs';
import { Minimatch } from 'minimatch';
import { setModifiedFileState } from 'mem-fs-editor/state';
const DEFAULT_DOC = 'This package file was generated by Begcode';
const packageInfoTransform = ({ javaRoots, javadocs }) => {
    const existingPackageInfoFiles = [];
    return passthrough(function (file) {
        if (file.path.endsWith('package-info.java')) {
            existingPackageInfoFiles.push(file.path);
            return;
        }
        for (const root of javaRoots) {
            if (file.path.startsWith(root)) {
                const directory = dirname(file.path);
                const packageName = relative(root, directory).replaceAll(/[/\\]/g, '.');
                const packageInfoFilePath = join(directory, 'package-info.java');
                if (existingPackageInfoFiles.includes(packageInfoFilePath)) {
                    return;
                }
                const packageInfoFile = loadFile(packageInfoFilePath);
                if (!packageInfoFile.contents) {
                    const packageJavadoc = javadocs?.[packageName] ?? DEFAULT_DOC;
                    packageInfoFile.contents = Buffer.from(`/**
 * ${packageJavadoc}
 */
package ${packageName};
`);
                    setModifiedFileState(packageInfoFile);
                    this.push(packageInfoFile);
                }
                existingPackageInfoFiles.push(packageInfoFilePath);
            }
        }
    });
};
export const matchMainJavaFiles = (srcMainJava) => new Minimatch(`**/${srcMainJava}/**/*.java`);
export default packageInfoTransform;
