"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.AgentCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const fs = __importStar(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const core_1 = require("@myycontext/core");
const hybridAIClient_1 = require("../utils/hybridAIClient");
const spinner_1 = require("../utils/spinner");
const ContextSyncer_1 = require("../services/ContextSyncer");
class AgentCommand {
    constructor(projectPath = process.cwd()) {
        this.projectPath = projectPath;
        this.manifestManager = new core_1.DesignManifestManager(projectPath);
        this.aiClient = new hybridAIClient_1.HybridAIClient();
        this.contextSyncer = new ContextSyncer_1.ContextSyncer(projectPath);
    }
    async execute(options) {
        const prompt = options.prompt;
        if (!prompt) {
            console.error(chalk_1.default.red("❌ No prompt provided. Usage: mycontext agent \"your reckless instruction\""));
            return;
        }
        const spinner = new spinner_1.EnhancedSpinner("Analyzing prompt against Living Brain...");
        spinner.start();
        try {
            // 1. Load the manifest
            const manifest = await this.manifestManager.loadDesignManifest();
            if (!manifest) {
                const contextPath = path_1.default.join(this.projectPath, ".mycontext", "context.json");
                const contextExists = await fs.pathExists(contextPath);
                if (contextExists) {
                    spinner.fail("Structured Design Manifest not found. Your 'context.json' may be in a legacy format.");
                    console.log(chalk_1.default.blue("\n➡️  To migrate, run:"), chalk_1.default.white("mycontext design analyze"));
                    console.log(chalk_1.default.gray("This will compute the 8-phase reasoning manifest required for Agent Mode.\n"));
                }
                else {
                    spinner.fail("No design manifest found. Run 'mycontext init' first.");
                }
                return;
            }
            // 2. Assessment Phase
            spinner.updateText("Consulting the Living Brain...");
            const assessment = await this.assessPrompt(prompt, manifest);
            spinner.succeed("Assessment complete.");
            // 3. Display Proposal
            this.displayProposal(assessment);
            // 4. Execution Phase
            if (options.execute) {
                await this.runEvolutionFlow(assessment, manifest, options);
            }
            else {
                console.log(chalk_1.default.gray("\nNext Step: Run with --execute (or -e) to apply these changes autonomously."));
            }
        }
        catch (error) {
            spinner.fail("Agent operation failed");
            console.error(chalk_1.default.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
        }
    }
    async runEvolutionFlow(assessment, currentManifest, options) {
        if (!options.yes) {
            const prompts = require("prompts");
            const response = await prompts({
                type: "confirm",
                name: "confirm",
                message: chalk_1.default.blue("Do you want the agent to evolve the Living Brain (Manifest + PRD) based on this assessment?"),
                initial: true
            });
            if (!response.confirm) {
                console.log(chalk_1.default.yellow("Aborted. No changes applied."));
                return;
            }
        }
        const spinner = new spinner_1.EnhancedSpinner("Evolving the Living Brain...");
        spinner.start();
        try {
            // 1. Evolve Manifest
            spinner.updateText("Updating context.json...");
            const evolvedManifest = await this.evolveManifest(assessment, currentManifest);
            await this.manifestManager.saveDesignManifest(evolvedManifest);
            // 2. Evolve Docs (Deterministic Projection)
            spinner.updateText("Projecting Living Brain to Markdown...");
            await this.contextSyncer.refreshMarkdownViews(evolvedManifest);
            spinner.succeed("Evolution complete. Human-readable views updated.");
            console.log(chalk_1.default.green("\n✨ The Living Brain has evolved. You can now use 'mycontext generate:components' or other commands to implement the changes."));
        }
        catch (error) {
            spinner.fail("Evolution failed");
            throw error;
        }
    }
    cleanJsonResponse(text) {
        let cleaned = text.trim();
        if (cleaned.startsWith("```json")) {
            cleaned = cleaned.substring(7);
        }
        else if (cleaned.startsWith("```")) {
            cleaned = cleaned.substring(3);
        }
        if (cleaned.endsWith("```")) {
            cleaned = cleaned.substring(0, cleaned.length - 3);
        }
        return cleaned.trim();
    }
    async evolveManifest(assessment, currentManifest) {
        const systemPrompt = `You are the MyContext Manifest Evolver.
Your task is to take the current design-manifest.json and a Change Proposal, and produce the UPDATED design-manifest.json.

Current Manifest:
${JSON.stringify(currentManifest, null, 2)}

Change Proposal:
${JSON.stringify(assessment, null, 2)}

OUTPUT ONLY THE FULL UPDATED JSON. Ensure the structure is valid and all required fields are preserved while incorporating the new features/changes.`;
        const response = await this.aiClient.generateText(systemPrompt, {
            temperature: 0.1,
            jsonMode: true
        });
        if (process.env.DEBUG || process.env.VERBOSE) {
            console.log(chalk_1.default.gray(`[AgentCommand] Evolved Manifest Response: ${response.text.substring(0, 200)}...`));
        }
        try {
            return JSON.parse(this.cleanJsonResponse(response.text));
        }
        catch (e) {
            console.error(chalk_1.default.red("Failed to parse evolved manifest JSON:"), response.text);
            throw new Error("AI failed to produce a valid evolved manifest JSON.");
        }
    }
    async assessPrompt(prompt, manifest) {
        const systemPrompt = `You are the MyContext Living Brain Orchestrator. 
Your job is to take a "reckless prompt" from a user and assess it against the project's "Physics Engine" (The Design Manifest).

The Design Manifest represents the immutable core of the project.
The user's prompt is a narrative request for change.

Your goal is to output a structured Manifest Change Proposal (JSON) that follows the Top-Down evolution flow:
1. **Schema-First Alignment**: How should the 8-phase reasoning manifest (functional_summary, visual_system, etc.) evolve to accommodate this request?
2. **Deterministic Tasks**: A sequence of terminal-runnable tasks or architectural updates.
3. **Boundary Check**: Does this prompt violate any existing PRD requirements or architectural constraints?
4. **Impact Score**: How much of the project is affected (Low/Medium/High)?

Current Manifest (Living Brain):
${JSON.stringify(manifest, null, 2)}

User Prompt:
"${prompt}"

OUTPUT ONLY VALID JSON in this format:
{
  "summary": "Brief summary of the proposed changes",
  "impact_score": "low|medium|high",
  "changes": [
    { "phase": "functional_summary|project_scope|context_gaps|design_brief|visual_system|component_hierarchy|implementation_plan|design_intent", "description": "What is changing in this phase?" }
  ],
  "tasks": [
    { "id": "task-uuid", "action": "Description of work", "type": "manifest_update|code_generation|filesystem|terminal" }
  ],
  "boundary_violations": ["List of concerns or contradictions with current manifest"]
}`;
        const response = await this.aiClient.generateText(systemPrompt, {
            temperature: 0.2,
            maxTokens: 2000,
            jsonMode: true
        });
        try {
            return JSON.parse(this.cleanJsonResponse(response.text));
        }
        catch (e) {
            console.error(chalk_1.default.red("Failed to parse JSON response from AI:"));
            console.log(chalk_1.default.gray(response.text));
            throw new Error(`AI failed to produce a valid JSON assessment: ${e instanceof Error ? e.message : String(e)}`);
        }
    }
    displayProposal(proposal) {
        console.log(chalk_1.default.blue.bold("\n📋 Manifest Change Proposal"));
        console.log(chalk_1.default.gray("─────────────────────────────────────────────────"));
        console.log(`${chalk_1.default.yellow("Summary:")} ${proposal.summary}`);
        console.log(`${chalk_1.default.yellow("Impact:")} ${this.formatImpact(proposal.impact_score)}`);
        console.log(chalk_1.default.blue("\n🧬 State Changes:"));
        proposal.changes.forEach((c) => {
            console.log(chalk_1.default.gray(`  • [${c.phase}] ${c.description}`));
        });
        console.log(chalk_1.default.blue("\n🏗️  Execution Plan (Deterministic Tasks):"));
        proposal.tasks.forEach((t, i) => {
            console.log(chalk_1.default.gray(`  ${i + 1}. [${t.type}] ${t.action}`));
        });
        if (proposal.boundary_violations && proposal.boundary_violations.length > 0) {
            console.log(chalk_1.default.red("\n⚠️  Boundary Violations / Concerns:"));
            proposal.boundary_violations.forEach((v) => {
                console.log(chalk_1.default.red(`  • ${v}`));
            });
        }
        console.log(chalk_1.default.gray("─────────────────────────────────────────────────"));
    }
    formatImpact(impact) {
        switch (impact.toLowerCase()) {
            case "low": return chalk_1.default.green(impact);
            case "medium": return chalk_1.default.yellow(impact);
            case "high": return chalk_1.default.red(impact);
            default: return impact;
        }
    }
}
exports.AgentCommand = AgentCommand;
//# sourceMappingURL=agent.js.map