import fs from 'node:fs';
import path from 'node:path';
import { gradialContentWatchPlugin, gradialDamAssetPlugin, devRefreshPort, devRefreshScript, } from '../dev/index.js';
// ---------------------------------------------------------------------------
// Static paths helper — for Astro SSG
// ---------------------------------------------------------------------------
/**
 * Generates static paths from the compiled content manifest for Astro.
 *
 * Usage in a catch-all page (e.g. `pages/[...slug].astro`):
 * ```ts
 * import { getGradialStaticPaths } from '@gradial/aci/astro';
 * export const getStaticPaths = getGradialStaticPaths;
 * ```
 */
export async function getGradialStaticPaths() {
    const { FileContentProvider } = await import('../providers/file.js');
    const { normalizeRoute } = await import('../content/routes.js');
    const provider = new FileContentProvider();
    const routes = await provider.listRoutes();
    return routes.map((entry) => {
        const normalized = normalizeRoute(entry.path);
        return {
            params: {
                slug: normalized === '/' ? undefined : normalized.replace(/^\/|\/$/g, '')
            }
        };
    });
}
export function gradialAstro(options = {}) {
    return {
        name: 'gradial-astro',
        hooks: {
            'astro:config:setup'({ injectScript, updateConfig }) {
                if (process.env.NODE_ENV === 'production') {
                    return;
                }
                if (devRefreshPort(options) > 0) {
                    injectScript('page', devRefreshScript(options));
                }
                updateConfig({
                    vite: {
                        plugins: [gradialDamAssetPlugin(options), gradialContentWatchPlugin(options)],
                    },
                });
            },
            'astro:build:done'({ dir }) {
                const siteDir = process.cwd();
                const compiledRoot = path.resolve(siteDir, options.compiledRoot || process.env.ACI_CONTENT_ROOT || '.aci/compiled');
                const source = path.join(compiledRoot, '.gradial-dam');
                if (!fs.existsSync(source))
                    return;
                const target = path.join(dir.pathname, '.gradial-dam');
                fs.rmSync(target, { recursive: true, force: true });
                fs.cpSync(source, target, { recursive: true });
            },
        },
    };
}
