"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeterministicScaffoldGenerator = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const nextjs_1 = require("./templates/nextjs");
class DeterministicScaffoldGenerator {
    constructor(targetDir = process.cwd()) {
        this.targetDir = targetDir;
    }
    async generate(fsr) {
        console.log(chalk_1.default.blue(`=== Scaffolding Feature: ${fsr.featureId} ===`));
        const usesSrc = fs_extra_1.default.existsSync(path_1.default.join(this.targetDir, 'src'));
        const baseDir = usesSrc ? path_1.default.join(this.targetDir, 'src') : this.targetDir;
        // 1. Generate Models/Types
        if (fsr.models && fsr.models.length > 0) {
            const typesDir = path_1.default.join(baseDir, 'types');
            await fs_extra_1.default.ensureDir(typesDir);
            const typesContent = (0, nextjs_1.generateTypesTemplate)(fsr.models);
            await fs_extra_1.default.writeFile(path_1.default.join(typesDir, `${fsr.featureId}.ts`), typesContent);
            console.log(chalk_1.default.green(`✓ Types generated: types/${fsr.featureId}.ts`));
        }
        // 2. Generate Server Actions
        if (fsr.serverActions && fsr.serverActions.length > 0) {
            const actionsDir = path_1.default.join(baseDir, 'app', 'actions');
            await fs_extra_1.default.ensureDir(actionsDir);
            const actionsContent = fsr.serverActions.map((a) => (0, nextjs_1.generateServerActionTemplate)(a, fsr.models)).join('\n\n');
            const cleanContent = `"use server";\n\nimport { revalidatePath } from "next/cache";\n\n` +
                actionsContent.replace(/"use server";\n\nimport { revalidatePath } from "next\/cache";\n\n/g, '');
            await fs_extra_1.default.writeFile(path_1.default.join(actionsDir, `${fsr.featureId}.ts`), cleanContent);
            console.log(chalk_1.default.green(`✓ Actions generated: app/actions/${fsr.featureId}.ts`));
        }
        // 3. Generate Components
        if (fsr.components && fsr.components.length > 0) {
            const componentsDir = path_1.default.join(baseDir, 'components');
            await fs_extra_1.default.ensureDir(componentsDir);
            for (const comp of fsr.components) {
                // Exclude the page entry point from standard components if it is defined as the entry component
                if (comp.name === fsr.entryPoint.component)
                    continue;
                const content = comp.type === 'server'
                    ? (0, nextjs_1.generateServerComponentTemplate)(comp)
                    : (0, nextjs_1.generateClientComponentTemplate)(comp);
                await fs_extra_1.default.writeFile(path_1.default.join(componentsDir, `${comp.name}.tsx`), content);
                console.log(chalk_1.default.green(`✓ Component generated: components/${comp.name}.tsx`));
            }
        }
        // 4. Generate Entry Point (Page)
        if (fsr.entryPoint.type === 'page') {
            const normalizedPath = fsr.entryPoint.path.startsWith('/') ? fsr.entryPoint.path.slice(1) : fsr.entryPoint.path;
            const pageDir = path_1.default.join(baseDir, 'app', normalizedPath);
            await fs_extra_1.default.ensureDir(pageDir);
            const rootComponent = fsr.components.find((c) => c.name === fsr.entryPoint.component);
            const childNames = rootComponent ? rootComponent.children || [] : [];
            const children = childNames.map(name => fsr.components.find(c => c.name === name)).filter(Boolean);
            const pageContent = (0, nextjs_1.generateNextPageTemplate)(fsr.entryPoint.component || 'Page', children, fsr.uiRules);
            await fs_extra_1.default.writeFile(path_1.default.join(pageDir, 'page.tsx'), pageContent);
            console.log(chalk_1.default.green(`✓ Page generated: app/${normalizedPath}/page.tsx`));
        }
        // 5. Generate Root Landing Page
        await this.generateRootLandingPage([{
                path: fsr.entryPoint.path,
                name: fsr.entryPoint.component || fsr.featureId
            }]);
        console.log(chalk_1.default.blue(`\n✅ Scaffolding complete for ${fsr.featureId}.`));
        console.log(chalk_1.default.gray(`Note: Import paths use "@/components" alias.`));
    }
    async generateRootLandingPage(extraRoutes = []) {
        const usesSrc = fs_extra_1.default.existsSync(path_1.default.join(this.targetDir, 'src'));
        const baseDir = usesSrc ? path_1.default.join(this.targetDir, 'src') : this.targetDir;
        const featuresDir = path_1.default.join(this.targetDir, '.mycontext', 'features');
        const routes = [...extraRoutes];
        if (await fs_extra_1.default.pathExists(featuresDir)) {
            const files = await fs_extra_1.default.readdir(featuresDir);
            for (const file of files) {
                if (file.endsWith('.fsr.json')) {
                    try {
                        const fData = await fs_extra_1.default.readJson(path_1.default.join(featuresDir, file));
                        if (fData.entryPoint && fData.entryPoint.path) {
                            // Avoid duplicates
                            if (!routes.some(r => r.path === fData.entryPoint.path)) {
                                routes.push({
                                    path: fData.entryPoint.path,
                                    name: fData.entryPoint.component || fData.featureId
                                });
                            }
                        }
                    }
                    catch (e) {
                        // ignore
                    }
                }
            }
        }
        const rootPagePath = path_1.default.join(baseDir, 'app', 'page.tsx');
        await fs_extra_1.default.ensureDir(path_1.default.join(baseDir, 'app'));
        const rootPageContent = (0, nextjs_1.generateRootLandingPageTemplate)(routes);
        await fs_extra_1.default.writeFile(rootPagePath, rootPageContent);
        console.log(chalk_1.default.green(`✓ Root landing page updated: app/page.tsx`));
    }
}
exports.DeterministicScaffoldGenerator = DeterministicScaffoldGenerator;
//# sourceMappingURL=scaffold.js.map