"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GenerateTodosCommand = void 0;
const hybridAIClient_1 = require("../utils/hybridAIClient");
const hostedApiClient_1 = require("../utils/hostedApiClient");
const chalk_1 = __importDefault(require("chalk"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
class GenerateTodosCommand {
    constructor() {
        this.aiClient = new hybridAIClient_1.HybridAIClient();
        this.hostedApiClient = new hostedApiClient_1.HostedApiClient();
    }
    register(program) {
        program
            .command("generate-todos")
            .description("Generate contextual todos from project context")
            .option("-c, --count <number>", "Number of todos to generate", "10")
            .option("-f, --focus <string>", "Focus area for todo generation")
            .option("-e, --energy <level>", "Energy level (low, medium, high)", "medium")
            .option("-x, --complexity <level>", "Complexity level (simple, moderate, complex)", "moderate")
            .option("-p, --project <id>", "Project ID for context")
            .action(async (options) => {
            await this.generateTodos(options);
        });
    }
    async generateTodos(options) {
        try {
            console.log(chalk_1.default.blue("🎯 Generating contextual todos...\n"));
            // Check if we have local AI keys
            if (this.hasLocalAIKeys()) {
                console.log(chalk_1.default.yellow("Using local AI providers..."));
                await this.generateWithLocalAI(options);
            }
            else {
                console.log(chalk_1.default.yellow("Using hosted MyContext AI..."));
                await this.generateWithHostedAI(options);
            }
            console.log(chalk_1.default.green("\n✅ Todo generation completed!"));
        }
        catch (error) {
            console.error(chalk_1.default.red("❌ Error generating todos:"), error);
            process.exit(1);
        }
    }
    hasLocalAIKeys() {
        return !!(process.env.MYCONTEXT_GITHUB_TOKEN ||
            process.env.MYCONTEXT_QWEN_API_KEY ||
            process.env.MYCONTEXT_GEMINI_API_KEY ||
            process.env.OPENAI_API_KEY ||
            process.env.ANTHROPIC_API_KEY ||
            process.env.HUGGINGFACE_API_KEY);
    }
    async generateWithLocalAI(options) {
        const context = await this.loadProjectContext();
        const count = parseInt(String(options.count || "10"));
        const focus = options.focus || "general development tasks";
        const energyLevel = options.energyLevel || "medium";
        const complexity = options.complexity || "moderate";
        const prompt = this.buildTodoGenerationPrompt(context, {
            count,
            focus,
            energyLevel,
            complexity,
        });
        try {
            const response = await this.aiClient.generateText(prompt, {
                temperature: 0.3,
                maxTokens: 4000,
            });
            const parsedTodos = this.parseTodosFromResponse(response.text);
            await this.saveTodos(parsedTodos, options.projectId);
            console.log(chalk_1.default.green(`Generated ${parsedTodos.length} contextual todos`));
            this.displayTodos(parsedTodos);
        }
        catch (error) {
            console.error(chalk_1.default.red("Error with local AI generation:"), error);
            throw error;
        }
    }
    async generateWithHostedAI(options) {
        const context = await this.loadProjectContext();
        const count = parseInt(String(options.count || "10"));
        const focus = options.focus || "general development tasks";
        const energyLevel = options.energyLevel || "medium";
        const complexity = options.complexity || "moderate";
        try {
            const response = await this.hostedApiClient.generateText(`Generate ${count} contextual todos for a ${complexity} complexity project focused on ${focus} with ${energyLevel} energy level.`, {
                context: JSON.stringify(context),
                temperature: 0.3,
                maxTokens: 4000,
            });
            const parsedTodos = this.parseTodosFromResponse(response.data?.message || response);
            await this.saveTodos(parsedTodos, options.projectId);
            console.log(chalk_1.default.green(`Generated ${parsedTodos.length} contextual todos`));
            this.displayTodos(parsedTodos);
        }
        catch (error) {
            console.error(chalk_1.default.red("Error with hosted AI generation:"), error);
            throw error;
        }
    }
    async loadProjectContext() {
        const contextPath = path_1.default.join(process.cwd(), ".mycontext");
        if (!fs_1.default.existsSync(contextPath)) {
            throw new Error("No .mycontext directory found. Run 'mycontext init' first.");
        }
        const context = {};
        // Load PRD
        const prdPath = path_1.default.join(contextPath, "01-prd.md");
        if (fs_1.default.existsSync(prdPath)) {
            context.prd = fs_1.default.readFileSync(prdPath, "utf8");
        }
        // Load types
        const typesPath = path_1.default.join(contextPath, "02-types.ts");
        if (fs_1.default.existsSync(typesPath)) {
            context.types = fs_1.default.readFileSync(typesPath, "utf8");
        }
        // Load component list
        const componentsPath = path_1.default.join(contextPath, "03-component-list.json");
        if (fs_1.default.existsSync(componentsPath)) {
            context.components = JSON.parse(fs_1.default.readFileSync(componentsPath, "utf8"));
        }
        // Load branding
        const brandingPath = path_1.default.join(contextPath, "04-branding.md");
        if (fs_1.default.existsSync(brandingPath)) {
            context.branding = fs_1.default.readFileSync(brandingPath, "utf8");
        }
        return context;
    }
    buildTodoGenerationPrompt(context, options) {
        return `You are a project management AI assistant. Generate ${options.count} contextual todos for a ${options.complexity} complexity project.

Project Context:
${JSON.stringify(context, null, 2)}

Focus Area: ${options.focus}
Energy Level: ${options.energyLevel}
Complexity: ${options.complexity}

For each todo, provide:
1. A clear, actionable title (max 60 characters)
2. A detailed description with full project context
3. Priority level (low, medium, high, urgent)
4. Estimated time in minutes
5. Relevant considerations based on project context
6. Tags for categorization
7. Dependencies (if any)

Format the response as a JSON array with this structure:
[
  {
    "title": "Todo title",
    "description": "Detailed description with project context",
    "priority": "medium",
    "estimatedTime": 120,
    "considerations": ["Consideration 1", "Consideration 2"],
    "tags": ["tag1", "tag2"],
    "dependencies": ["todo-id-1", "todo-id-2"]
  }
]

Make sure each todo is:
- Specific and actionable
- Contextually relevant to the project
- Appropriate for the specified energy level and complexity
- Includes all necessary context for understanding
- Realistic in terms of time estimation
- Properly categorized with relevant tags`;
    }
    parseTodosFromResponse(response) {
        try {
            // Try to extract JSON from the response
            const jsonMatch = response.match(/\[[\s\S]*\]/);
            if (jsonMatch) {
                return JSON.parse(jsonMatch[0]);
            }
            // Fallback: create basic todos from text
            const lines = response.split("\n").filter((line) => line.trim());
            const todos = [];
            for (let i = 0; i < Math.min(lines.length, 10); i++) {
                const line = lines[i]?.trim() || "";
                if (line && !line.startsWith("#") && !line.startsWith("*")) {
                    todos.push({
                        title: line.substring(0, 60),
                        description: line,
                        priority: "medium",
                        estimatedTime: 60,
                        considerations: ["Generated from project context"],
                        tags: ["generated"],
                        dependencies: [],
                    });
                }
            }
            return todos;
        }
        catch (error) {
            console.error("Error parsing todos from response:", error);
            return [];
        }
    }
    async saveTodos(todos, projectId) {
        const todosPath = path_1.default.join(process.cwd(), ".mycontext", "todos.json");
        // Load existing todos
        let existingTodos = [];
        if (fs_1.default.existsSync(todosPath)) {
            try {
                existingTodos = JSON.parse(fs_1.default.readFileSync(todosPath, "utf8"));
            }
            catch (error) {
                console.warn("Could not load existing todos, starting fresh");
            }
        }
        // Add new todos with IDs
        const newTodos = todos.map((todo, index) => ({
            id: `todo-${Date.now()}-${index}`,
            ...todo,
            status: "todo",
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
            projectId: projectId || "default",
        }));
        const allTodos = [...existingTodos, ...newTodos];
        // Ensure .mycontext directory exists
        const contextDir = path_1.default.dirname(todosPath);
        if (!fs_1.default.existsSync(contextDir)) {
            fs_1.default.mkdirSync(contextDir, { recursive: true });
        }
        fs_1.default.writeFileSync(todosPath, JSON.stringify(allTodos, null, 2));
    }
    displayTodos(todos) {
        console.log(chalk_1.default.blue("\n📋 Generated Todos:\n"));
        todos.forEach((todo, index) => {
            console.log(chalk_1.default.cyan(`${index + 1}. ${todo.title}`));
            console.log(chalk_1.default.gray(`   Priority: ${todo.priority} | Time: ${todo.estimatedTime}min`));
            console.log(chalk_1.default.gray(`   Tags: ${todo.tags.join(", ")}`));
            console.log(chalk_1.default.white(`   ${todo.description}`));
            if (todo.considerations && todo.considerations.length > 0) {
                console.log(chalk_1.default.yellow(`   Considerations: ${todo.considerations.join(", ")}`));
            }
            console.log();
        });
    }
}
exports.GenerateTodosCommand = GenerateTodosCommand;
//# sourceMappingURL=generate-todos.js.map