"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.AgentFlowCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const spinner_1 = require("../utils/spinner");
const SubAgentOrchestrator_1 = require("../agents/orchestrator/SubAgentOrchestrator");
const CodeGenSubAgent_1 = require("../agents/implementations/CodeGenSubAgent");
const QASubAgent_1 = require("../agents/implementations/QASubAgent");
const DocsSubAgent_1 = require("../agents/implementations/DocsSubAgent");
const CyberRedTeamAgent_1 = require("../agents/implementations/CyberRedTeamAgent");
const AgentCommunicationManager_1 = require("../agents/communication/AgentCommunicationManager");
const AgentCommunication_1 = require("../agents/interfaces/AgentCommunication");
const fs = __importStar(require("fs-extra"));
const path_1 = __importDefault(require("path"));
class AgentFlowCommand {
    constructor() {
        this.orchestrator = new SubAgentOrchestrator_1.SubAgentOrchestrator();
        // Register agents
        this.orchestrator.registerAgent(new CodeGenSubAgent_1.CodeGenSubAgent());
        this.orchestrator.registerAgent(new QASubAgent_1.QASubAgent());
        this.orchestrator.registerAgent(new DocsSubAgent_1.DocsSubAgent());
        this.orchestrator.registerAgent(new CyberRedTeamAgent_1.CyberRedTeamAgent());
        // Initialize communication manager
        this.communicationManager = new AgentCommunicationManager_1.AgentCommunicationManager(this.orchestrator);
    }
    async execute(action, options) {
        const spinner = new spinner_1.EnhancedSpinner(`Running agent flow: ${action}`);
        try {
            spinner.start();
            switch (action) {
                case "generate-context":
                    await this.runContextGenerationFlow(options, spinner);
                    break;
                case "generate-components":
                    await this.runComponentGenerationFlow(options, spinner);
                    break;
                case "validate-workflow":
                    await this.runValidationWorkflow(options, spinner);
                    break;
                default:
                    throw new Error(`Unknown agent flow action: ${action}`);
            }
            spinner.success({ text: `Agent flow completed: ${action}` });
            this.printFlowSummary(action);
        }
        catch (error) {
            spinner.error({ text: `Agent flow failed: ${error.message}` });
            throw error;
        }
    }
    async runContextGenerationFlow(options, spinner) {
        spinner.updateText("Orchestrating context generation agents...");
        // Read existing context
        const context = await this.loadProjectContext();
        const workflowConfig = {
            pattern: AgentCommunication_1.CommunicationPattern.AUTO_ORCHESTRATION,
            agents: ["CodeGenSubAgent", "QASubAgent", "DocsSubAgent"],
            retryLimit: options.retryLimit || 2,
            qualityThreshold: options.qualityThreshold || 0.7,
            timeoutMs: 60000, // 1 minute for faster UX
            enableAutoTransition: true,
        };
        // Run auto workflow
        const result = await this.communicationManager.runAutoWorkflow("CodeGenSubAgent", context, workflowConfig);
        if (!result.success) {
            throw new Error("Agent communication workflow failed");
        }
        // Save results
        await this.saveWorkflowResults("context-generation", result);
        console.log(chalk_1.default.green(`\n✅ Context generation completed with ${result.messages.length} agent messages`));
    }
    async runComponentGenerationFlow(options, spinner) {
        spinner.updateText("Orchestrating component generation agents...");
        const context = await this.loadProjectContext();
        // Add component-specific context
        if (options.target) {
            context.userPrompt = `Generate component: ${options.target}`;
        }
        const workflowConfig = {
            pattern: options.mode === "validation"
                ? AgentCommunication_1.CommunicationPattern.VALIDATION_CHAIN
                : AgentCommunication_1.CommunicationPattern.SEQUENTIAL,
            agents: ["CodeGenSubAgent", "QASubAgent", "DocsSubAgent"],
            retryLimit: options.retryLimit || 3,
            qualityThreshold: options.qualityThreshold || 0.8,
            timeoutMs: 60000, // 1 minute for faster UX
            enableAutoTransition: true,
        };
        const result = await this.communicationManager.runAutoWorkflow("CodeGenSubAgent", context, workflowConfig);
        if (!result.success) {
            throw new Error("Component generation workflow failed");
        }
        await this.saveWorkflowResults("component-generation", result);
        console.log(chalk_1.default.green(`\n✅ Component generation completed`));
        console.log(chalk_1.default.gray(`   Generated: ${Object.keys(result.outputs).length} outputs`));
        console.log(chalk_1.default.gray(`   Messages: ${result.messages.length} agent communications`));
    }
    async runValidationWorkflow(options, spinner) {
        spinner.updateText("Running validation workflow...");
        // Test the communication system
        const testMessage = {
            id: "test-message",
            from: "system",
            to: "CodeGenSubAgent",
            type: "request",
            payload: { test: true },
            timestamp: new Date().toISOString(),
        };
        await this.communicationManager.sendMessage(testMessage);
        const received = await this.communicationManager.receiveMessage("CodeGenSubAgent");
        if (!received) {
            throw new Error("Agent communication validation failed");
        }
        console.log(chalk_1.default.green("\n✅ Agent communication system validated"));
        console.log(chalk_1.default.gray("   Message sending/receiving: OK"));
        console.log(chalk_1.default.gray("   Message persistence: OK"));
    }
    async loadProjectContext() {
        const contextDir = path_1.default.join(process.cwd(), ".mycontext");
        const context = {};
        // Load existing context files
        try {
            const prdPath = path_1.default.join(contextDir, "01-prd.md");
            if (await fs.pathExists(prdPath)) {
                context.prd = await fs.readFile(prdPath, "utf8");
            }
            const typesPath = path_1.default.join(contextDir, "02-types.ts");
            if (await fs.pathExists(typesPath)) {
                context.types = await fs.readFile(typesPath, "utf8");
            }
            const brandPath = path_1.default.join(contextDir, "03-branding.md");
            if (await fs.pathExists(brandPath)) {
                context.brand = await fs.readFile(brandPath, "utf8");
            }
            const compListPath = path_1.default.join(contextDir, "04-component-list.json");
            if (await fs.pathExists(compListPath)) {
                const compListRaw = await fs.readFile(compListPath, "utf8");
                context.componentList = JSON.parse(compListRaw);
            }
            const structurePath = path_1.default.join(contextDir, "05-project-structure.md");
            if (await fs.pathExists(structurePath)) {
                context.projectStructure = await fs.readFile(structurePath, "utf8");
            }
        }
        catch (error) {
            console.log(chalk_1.default.yellow("⚠️ Some context files could not be loaded"));
        }
        return context;
    }
    async saveWorkflowResults(workflowType, result) {
        const resultsDir = path_1.default.join(process.cwd(), ".mycontext", "agent-workflows");
        await fs.ensureDir(resultsDir);
        const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
        const resultsFile = path_1.default.join(resultsDir, `${workflowType}-${timestamp}.json`);
        await fs.writeJson(resultsFile, {
            workflowType,
            timestamp: new Date().toISOString(),
            success: result.success,
            outputs: result.outputs,
            messages: result.messages,
            summary: {
                totalOutputs: Object.keys(result.outputs).length,
                totalMessages: result.messages.length,
                agents: Object.keys(result.outputs),
            },
        }, { spaces: 2 });
        console.log(chalk_1.default.gray(`   Workflow results saved: ${resultsFile}`));
    }
    printFlowSummary(action) {
        console.log(chalk_1.default.blue("\n➡️ Next Steps:"));
        switch (action) {
            case "generate-context":
                console.log(chalk_1.default.gray("   mycontext agent-flow generate-components"));
                console.log(chalk_1.default.gray("   mycontext generate-components all"));
                break;
            case "generate-components":
                console.log(chalk_1.default.gray("   Preview at: https://studio.mycontext.app"));
                console.log(chalk_1.default.gray("   mycontext list components --local"));
                break;
            case "validate-workflow":
                console.log(chalk_1.default.gray("   Agent communication system is working"));
                console.log(chalk_1.default.gray("   Ready for production agent workflows"));
                break;
        }
        console.log(chalk_1.default.blue("\n🔍 Debug:"));
        console.log(chalk_1.default.gray("   Check .mycontext/agent-logs/ for communication history"));
        console.log(chalk_1.default.gray("   Check .mycontext/agent-workflows/ for workflow results"));
    }
}
exports.AgentFlowCommand = AgentFlowCommand;
//# sourceMappingURL=agent-flow.js.map