"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompilePageCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs-extra"));
const LandingPageOrchestrator_1 = require("../services/LandingPageOrchestrator");
/**
 * CompilePageCommand orchestrates the Manifest-Driven Landing Page Compilation pipeline.
 */
class CompilePageCommand {
    async execute(options) {
        const projectPath = options.project || process.cwd();
        const benchmark = !!options.benchmark;
        // Determine target output directory
        let outputDir = options.output;
        if (!outputDir) {
            // Check typical folder structures
            if (await fs.pathExists(path.join(projectPath, "apps/site"))) {
                outputDir = path.join(projectPath, "apps/site/components/landing-page");
            }
            else if (await fs.pathExists(path.join(projectPath, "../../apps/site"))) {
                outputDir = path.join(projectPath, "../../apps/site/components/landing-page");
            }
            else if (await fs.pathExists(path.join(projectPath, "src/components"))) {
                outputDir = path.join(projectPath, "src/components/landing-page");
            }
            else {
                outputDir = path.join(projectPath, "components/landing-page");
            }
        }
        outputDir = path.resolve(projectPath, outputDir);
        console.log(chalk_1.default.bold.blue("🚀 Starting Manifest-Driven Landing Page Compilation"));
        console.log(chalk_1.default.gray(`Project root: ${projectPath}`));
        console.log(chalk_1.default.gray(`Target output: ${outputDir}`));
        if (benchmark) {
            console.log(chalk_1.default.magenta("📊 Benchmark mode enabled. Generating direct prompting baseline for comparison."));
        }
        try {
            const orchestrator = new LandingPageOrchestrator_1.LandingPageOrchestrator(projectPath, outputDir, options.verbose, !!options.fresh);
            // Auto-run through all 14 stages
            console.log(chalk_1.default.cyan("\n[Pipeline] Running 14-stage landing page compiler..."));
            console.log(chalk_1.default.gray("  Stages: BASELINE_CHECK → CONTEXT → NARRATIVE → SECTION_MANIFEST →"));
            console.log(chalk_1.default.gray("          COMPONENT_INVENTORY → PRIMITIVE_MAPPING → SKELETON →"));
            console.log(chalk_1.default.gray("          CONTENT_POPULATED → SECTION_VALIDATED → CLASSNAME_REFINED →"));
            console.log(chalk_1.default.gray("          FINAL_VALIDATED\n"));
            let maxIterations = 20; // Safety limit
            while (maxIterations-- > 0) {
                const currentStage = orchestrator.state.stage;
                // Check if we've reached a terminal stage
                if (currentStage === "FINAL_VALIDATED" || currentStage === "SELF_HEALED") {
                    break;
                }
                await orchestrator.advance();
                const newStage = orchestrator.state.stage;
                // Report progress - use newStage variable to avoid type narrowing issues
                const stageValue = newStage;
                if (stageValue === "BASELINE_CHECK") {
                    console.log(chalk_1.default.green("✔ [Stage 1/14] Baseline check completed"));
                }
                else if (stageValue === "CONTEXT_GENERATED") {
                    console.log(chalk_1.default.green("✔ [Stage 2/14] Project context extracted"));
                }
                else if (stageValue === "NARRATIVE_GENERATED") {
                    console.log(chalk_1.default.green("✔ [Stage 3/14] Narrative strategy generated"));
                }
                else if (stageValue === "SECTION_MANIFEST_GENERATED") {
                    console.log(chalk_1.default.green("✔ [Stage 4/14] Section manifest generated"));
                }
                else if (stageValue === "COMPONENT_INVENTORY_GENERATED") {
                    console.log(chalk_1.default.green("✔ [Stage 5/14] Component inventory generated"));
                }
                else if (stageValue === "PRIMITIVE_MAPPING_GENERATED") {
                    console.log(chalk_1.default.green("✔ [Stage 6/14] Primitive mapping completed"));
                }
                else if (stageValue === "SKELETON_GENERATED") {
                    console.log(chalk_1.default.green(`✔ [Stage 8/14] ${orchestrator.state.skeletons?.length || 0} component skeletons generated`));
                }
                else if (stageValue === "CONTENT_POPULATED") {
                    console.log(chalk_1.default.green("✔ [Stage 9/14] Content populated in components"));
                }
                else if (stageValue === "SECTION_VALIDATED") {
                    console.log(chalk_1.default.green("✔ [Stage 10/14] Per-section validation passed"));
                }
                else if (stageValue === "CLASSNAME_REFINED") {
                    console.log(chalk_1.default.green("✔ [Stage 11/14] Constrained design refinement completed"));
                }
                else if (stageValue === "FINAL_VALIDATED") {
                    console.log(chalk_1.default.green("✔ [Stage 12/14] Final validation passed"));
                }
                else if (stageValue === "SELF_HEALED") {
                    console.log(chalk_1.default.green("✔ [Stage 13/14] Self-healing completed"));
                }
                // Prevent infinite loop
                if (currentStage === newStage) {
                    console.log(chalk_1.default.red(`✗ Pipeline stuck at stage: ${currentStage}`));
                    break;
                }
            }
            if (benchmark) {
                console.log(chalk_1.default.cyan("\n[Benchmark] Generating Direct Prompt Baseline..."));
                await orchestrator.generateDirectPromptBaseline();
                console.log(chalk_1.default.green("✔ Baseline generated."));
                console.log(chalk_1.default.bold.magenta("\n📊 Benchmark Generation Complete!"));
                console.log(chalk_1.default.gray(`Compare the two outputs in:\n - Pipeline result: ${outputDir}\n - Baseline: ${path.join(path.dirname(outputDir), "landing-page-baseline")}`));
            }
            console.log(chalk_1.default.bold.green("\n🎉 Landing Page Compilation Completed Successfully!"));
            console.log(chalk_1.default.gray(`Your design-refined, accessible components are ready at: ${outputDir}`));
            console.log("\n" + orchestrator.getCompilationSummary());
        }
        catch (error) {
            console.error(chalk_1.default.red("❌ Landing page compilation failed:"), error);
            throw error;
        }
    }
}
exports.CompilePageCommand = CompilePageCommand;
//# sourceMappingURL=compile-page.js.map