/* eslint-disable no-console */
import { glob } from 'glob';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { tsDocgen } from './tsDocGen.js';
import { getConfig } from './getConfig.js';
function getTsDocName(name, variant) {
    return `${name}${variant ? `-${variant}` : ''}`;
}
function getTsDocNameVariant(source) {
    if (source.includes('next')) {
        return 'next';
    }
    if (source.includes('deprecated')) {
        return 'deprecated';
    }
}
async function getFiles(root, globs) {
    const files = await Promise.all(globs.map(async ({ include, exclude }) => {
        const files = await glob(include, { cwd: root, ignore: exclude, absolute: true });
        return files;
    }));
    return files.flat();
}
async function getPropsData(files, verbose) {
    const perFilePropsData = await Promise.all(files.map(async (file) => {
        if (verbose) {
            console.log(`Parsing props from ${file}`);
        }
        const props = (await tsDocgen(file));
        const tsDocs = props.reduce((acc, { name, description, props }) => {
            const key = getTsDocName(name, getTsDocNameVariant(file));
            return { ...acc, [key]: { name, description, props } };
        }, {});
        return tsDocs;
    }));
    const combinedPropsData = perFilePropsData.reduce((acc, props) => {
        Object.keys(props).forEach((key) => {
            const propsData = props[key];
            if (acc[key]) {
                acc[key].props = [...acc[key].props, ...propsData.props];
            }
            else {
                acc[key] = propsData;
            }
        });
        return acc;
    }, {});
    return combinedPropsData;
}
export async function buildPropsData(rootDir, configFile, verbose) {
    const verboseModeLog = (...messages) => {
        if (verbose) {
            console.log(...messages);
        }
    };
    verboseModeLog('Beginning props data build');
    const config = await getConfig(configFile);
    if (!config) {
        console.error('No config found, please run the `setup` command or manually create a pf-docs.config.mjs file');
        return;
    }
    const { propsGlobs, outputDir } = config;
    if (!propsGlobs) {
        console.error('No props data found in config');
        return;
    }
    const files = await getFiles(rootDir, propsGlobs);
    verboseModeLog(`Found ${files.length} files to parse`);
    const propsData = await getPropsData(files, verbose);
    const propsFile = join(outputDir, 'props.json');
    const absolutePropsFilePath = join(process.cwd(), propsFile);
    verboseModeLog(`Writing props data to ${absolutePropsFilePath}`);
    await writeFile(propsFile, JSON.stringify(propsData));
}
