"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.GenerateActionsCommand = void 0;
exports.registerGenerateActionsCommand = registerGenerateActionsCommand;
const chalk_1 = __importDefault(require("chalk"));
const fs = __importStar(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const spinner_1 = require("../utils/spinner");
const logger_1 = require("../utils/logger");
const hybridAIClient_1 = require("../utils/hybridAIClient");
/**
 * Generate Actions Command
 * Creates a manifest of user/system actions needed to hook UI to backend/DB
 */
class GenerateActionsCommand {
    constructor() {
        this.spinner = new spinner_1.EnhancedSpinner("Loading context files...");
        this.aiClient = new hybridAIClient_1.HybridAIClient();
        this.contextDir = ".mycontext";
    }
    async execute(options = {}) {
        this.spinner.start();
        try {
            const context = await this.loadContext();
            if (!context.components && !context.features && !context.technicalSpecs) {
                this.spinner.fail("No context files found");
                console.log(chalk_1.default.yellow("\n💡 Generate components manifest first:"));
                console.log(chalk_1.default.cyan("   mycontext generate:components-manifest\n"));
                return;
            }
            this.spinner.updateText("Analyzing components and features for actions...");
            const prompt = this.buildActionsPrompt(context);
            this.spinner.updateText("Generating actions manifest with AI...");
            const response = await this.aiClient.generateText(prompt, {
                maxTokens: 8192,
                temperature: 0.3,
            });
            if (!response) {
                throw new Error("AI generation failed");
            }
            const actions = this.parseActionsResponse(response.text);
            const markdown = this.generateMarkdown(actions);
            const outputPath = options.output || path_1.default.join(this.contextDir, "04-actions.md");
            await fs.ensureDir(path_1.default.dirname(outputPath));
            await fs.writeFile(outputPath, markdown, "utf-8");
            // Also generate JSON
            const jsonPath = path_1.default.join(this.contextDir, "04-actions.json");
            await fs.writeFile(jsonPath, JSON.stringify(actions, null, 2), "utf-8");
            this.spinner.succeed("Actions manifest generated!");
            console.log(chalk_1.default.green(`\n✅ Actions manifest generated`));
            console.log(chalk_1.default.gray(`   User Actions: ${actions.userActions.length}`));
            console.log(chalk_1.default.gray(`   System Actions: ${actions.systemActions.length}`));
            console.log(chalk_1.default.gray(`   DB Tables: ${actions.dbSchemaHints.length}`));
            console.log(chalk_1.default.gray(`\n   Saved to: ${outputPath}\n`));
            // Print overview
            console.log(chalk_1.default.bold("🎬 User Actions Overview:"));
            actions.userActions.slice(0, 5).forEach(action => {
                console.log(chalk_1.default.cyan(`   ${action.name}`));
                console.log(chalk_1.default.gray(`      ${action.trigger} → ${action.backendHook}`));
            });
            if (actions.userActions.length > 5) {
                console.log(chalk_1.default.gray(`   ... and ${actions.userActions.length - 5} more`));
            }
            console.log(chalk_1.default.yellow("\n💡 Next Steps:"));
            console.log(chalk_1.default.gray("   1. Review actions and customize for your backend"));
            console.log(chalk_1.default.gray("   2. mycontext generate-components"));
            console.log(chalk_1.default.gray("   3. Implement backend endpoints"));
        }
        catch (error) {
            this.spinner.fail(`Failed to generate actions manifest: ${error.message}`);
            logger_1.logger.error("Actions generation error:", error);
        }
    }
    async loadContext() {
        const context = {};
        const dir = this.contextDir;
        const files = [
            { key: "components", path: "03-components.md" },
            { key: "screensList", path: "02-screens-list.md" },
            { key: "features", path: "01a-features.md" },
            { key: "technicalSpecs", path: "01d-technical-specs.md" },
            { key: "types", path: "02-types.ts" },
            { key: "userFlows", path: "01b-user-flows.md" },
        ];
        for (const file of files) {
            const filePath = path_1.default.join(dir, file.path);
            if (await fs.pathExists(filePath)) {
                context[file.key] = await fs.readFile(filePath, "utf-8");
            }
        }
        return context;
    }
    buildActionsPrompt(context) {
        let prompt = `You are a full-stack architect. Analyze the following project context and extract ALL actions needed to connect the UI to backend/database.

Categorize actions as:
1. **User Actions**: Triggered by user interaction (clicks, form submits, etc.)
2. **System Actions**: Triggered by the system (timers, webhooks, background jobs)
3. **DB Schema Hints**: What database tables/fields are needed

For User Actions, provide:
- name: Action name (camelCase, e.g., "createTask")
- trigger: What triggers it (e.g., "Submit task form")
- handler: Frontend handler function name
- description: What it does
- backendHook: API endpoint (e.g., "POST /api/tasks")
- httpMethod: HTTP method
- payload: Request body shape
- response: Response shape

For System Actions, provide:
- name: Action name
- trigger: What triggers it (e.g., "Every 5 minutes", "On task create")
- implementation: Hook or function name
- description: What it does

For DB Schema Hints, provide:
- table: Table/collection name
- fields: Array of field names with types
- relationships: Foreign keys or references

OUTPUT FORMAT (JSON):
\`\`\`json
{
  "userActions": [
    {
      "name": "createTask",
      "trigger": "Submit create task form",
      "handler": "handleCreateTask",
      "description": "Creates a new task in the database",
      "backendHook": "POST /api/tasks",
      "httpMethod": "POST",
      "payload": "{ title: string, description?: string, priority: Priority }",
      "response": "{ id: string, ...task }"
    }
  ],
  "systemActions": [
    {
      "name": "autoSaveDraft",
      "trigger": "5 second debounce on form change",
      "implementation": "useDraftAutoSave()",
      "description": "Automatically saves form draft to localStorage"
    }
  ],
  "dbSchemaHints": [
    {
      "table": "tasks",
      "fields": ["id: string", "title: string", "completed: boolean", "userId: string", "createdAt: Date"],
      "relationships": ["userId -> users.id"]
    }
  ]
}
\`\`\`

PROJECT CONTEXT:
`;
        if (context.components) {
            prompt += `\n## Components (with actions needed):\n${context.components.substring(0, 3000)}\n`;
        }
        if (context.technicalSpecs) {
            prompt += `\n## Technical Specs (API endpoints):\n${context.technicalSpecs.substring(0, 2500)}\n`;
        }
        if (context.features) {
            prompt += `\n## Features:\n${context.features.substring(0, 2000)}\n`;
        }
        if (context.types) {
            prompt += `\n## TypeScript Types:\n${context.types.substring(0, 1500)}\n`;
        }
        if (context.userFlows) {
            prompt += `\n## User Flows:\n${context.userFlows.substring(0, 1500)}\n`;
        }
        prompt += `
Be comprehensive - include CRUD operations for all entities, auth actions, and any background processes.
Output ONLY the JSON object.`;
        return prompt;
    }
    parseActionsResponse(response) {
        try {
            const jsonMatch = response.match(/\{[\s\S]*\}/);
            if (!jsonMatch) {
                logger_1.logger.warn("Could not find JSON in response");
                return { userActions: [], systemActions: [], dbSchemaHints: [] };
            }
            const parsed = JSON.parse(jsonMatch[0]);
            return {
                userActions: (parsed.userActions || []).map((a) => ({
                    name: a.name || "",
                    trigger: a.trigger || "",
                    handler: a.handler || a.name,
                    description: a.description || "",
                    backendHook: a.backendHook || "",
                    httpMethod: a.httpMethod,
                    payload: a.payload,
                    response: a.response,
                })),
                systemActions: (parsed.systemActions || []).map((a) => ({
                    name: a.name || "",
                    trigger: a.trigger || "",
                    implementation: a.implementation || "",
                    description: a.description || "",
                })),
                dbSchemaHints: (parsed.dbSchemaHints || []).map((h) => ({
                    table: h.table || "",
                    fields: h.fields || [],
                    relationships: h.relationships,
                })),
            };
        }
        catch (error) {
            logger_1.logger.error("Failed to parse actions response:", error);
            return { userActions: [], systemActions: [], dbSchemaHints: [] };
        }
    }
    generateMarkdown(actions) {
        let md = `# Actions Manifest

> Complete list of actions needed to connect UI to backend/database.

## Summary

| Category | Count |
|----------|-------|
| User Actions | ${actions.userActions.length} |
| System Actions | ${actions.systemActions.length} |
| Database Tables | ${actions.dbSchemaHints.length} |

---

## User Actions

These are actions triggered by user interaction (clicks, form submits, etc.).

| Action | Trigger | Backend Hook | Method |
|--------|---------|--------------|--------|
`;
        actions.userActions.forEach(action => {
            md += `| \`${action.name}\` | ${action.trigger} | \`${action.backendHook}\` | ${action.httpMethod || "N/A"} |\n`;
        });
        md += `\n### Action Details\n\n`;
        actions.userActions.forEach(action => {
            md += `#### ${action.name}\n\n`;
            md += `- **Description**: ${action.description}\n`;
            md += `- **Trigger**: ${action.trigger}\n`;
            md += `- **Handler**: \`${action.handler}\`\n`;
            md += `- **Backend**: \`${action.backendHook}\`\n`;
            if (action.payload) {
                md += `- **Payload**: \`${action.payload}\`\n`;
            }
            if (action.response) {
                md += `- **Response**: \`${action.response}\`\n`;
            }
            md += `\n`;
        });
        md += `---\n\n## System Actions\n\nThese are actions triggered by the system (timers, webhooks, background jobs).\n\n`;
        if (actions.systemActions.length === 0) {
            md += `*No system actions identified*\n\n`;
        }
        else {
            md += `| Action | Trigger | Implementation |\n|--------|---------|----------------|\n`;
            actions.systemActions.forEach(action => {
                md += `| \`${action.name}\` | ${action.trigger} | \`${action.implementation}\` |\n`;
            });
            md += `\n`;
        }
        md += `---\n\n## Database Schema Hints\n\nBased on the actions above, you'll need these database structures:\n\n`;
        if (actions.dbSchemaHints.length === 0) {
            md += `*No specific schema hints generated*\n\n`;
        }
        else {
            actions.dbSchemaHints.forEach(hint => {
                md += `### \`${hint.table}\`\n\n`;
                md += `**Fields**:\n`;
                hint.fields.forEach(field => {
                    md += `- \`${field}\`\n`;
                });
                if (hint.relationships && hint.relationships.length > 0) {
                    md += `\n**Relationships**:\n`;
                    hint.relationships.forEach(rel => {
                        md += `- ${rel}\n`;
                    });
                }
                md += `\n`;
            });
        }
        md += `---
*Generated by MyContext CLI*
*Last updated: ${new Date().toISOString()}*
`;
        return md;
    }
}
exports.GenerateActionsCommand = GenerateActionsCommand;
function registerGenerateActionsCommand(program) {
    program
        .command("generate:actions")
        .alias("ga")
        .description("Generate actions manifest for connecting UI to backend/database")
        .option("-o, --output <path>", "Output file path", ".mycontext/04-actions.md")
        .option("-v, --verbose", "Enable verbose logging")
        .option("--include-schema", "Include detailed DB schema suggestions")
        .action(async (options) => {
        const command = new GenerateActionsCommand();
        await command.execute(options);
    });
}
//# sourceMappingURL=generate-actions.js.map