import path from "path";
import { getStoryFiles, detectUsedPackages, parseTsConfig, exec, filterParsedPathsByUsedPackages } from "../../../../libs/common/src/storybook/storybook-utils";
const config = {
    stories: ['../**/*.@(mdx|stories.@(js|ts|tsx))'],
    addons: [
        '@storybook/addon-essentials',
        '@storybook/addon-interactions',
        'storybook-dark-mode'
    ],
    docs: {
        defaultName: 'Documentation',
        autodocs: 'tag'
    },
    framework: {
        name: '@storybook/web-components-vite',
        options: {}
    },
    // Async viteFinal to build dependent packages before finalizing configuration.
    viteFinal: async (config) => {
        const storyFiles = getStoryFiles(path.resolve(__dirname, '../'));
        const usedPackages = detectUsedPackages(storyFiles);
        const buildPromises = usedPackages.map(async (pkg) => {
            try {
                console.log(`Building package ${pkg}...`);
                const { stdout, stderr } = await exec(`nx run ${pkg}:build`);
                console.log(`Built package ${pkg}: ${stdout}`);
                if (stderr) {
                    console.error(`Build warning/error for package ${pkg}: ${stderr}`);
                }
            }
            catch (error) {
                console.error(`Error building package ${pkg}:`, error);
            }
        });
        await Promise.all(buildPromises);
        const parsedPaths = parseTsConfig() || {};
        const filteredParsedPaths = filterParsedPathsByUsedPackages(parsedPaths, usedPackages);
        return Object.assign(Object.assign({}, config), { resolve: {
                alias: Object.assign({}, filteredParsedPaths)
            }, define: {
                process: {
                    env: {}
                }
            } });
    }
};
export default config;
