"use strict";
/**
 * 📝 Todo Command - Claude-Inspired Task Management
 * Transform low scores into exciting gamified todo lists
 */
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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.todoCommand = todoCommand;
const faf_compiler_1 = require("../compiler/faf-compiler");
const file_utils_1 = require("../utils/file-utils");
const claude_todo_engine_1 = require("../engines/claude-todo-engine");
const championship_style_1 = require("../utils/championship-style");
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const yaml_1 = require("../fix-once/yaml");
/**
 * Main improve command - generates Claude-inspired todo lists
 */
async function todoCommand(options = {}) {
    try {
        const startTime = Date.now();
        console.log(championship_style_1.FAF_COLORS.fafCyan(`${championship_style_1.FAF_ICONS.clipboard} Claude-Inspired Todo System`));
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}${championship_style_1.BRAND_MESSAGES.optimization}`);
        const fafPath = await (0, file_utils_1.findFafFile)();
        if (!fafPath) {
            console.log(`${championship_style_1.FAF_COLORS.fafOrange('└─ ')}No .faf file found. Run ${championship_style_1.FAF_COLORS.fafCyan('faf init')} first.`);
            return;
        }
        if (options.complete) {
            await completeTask(options.complete, fafPath);
            return;
        }
        if (options.reset) {
            await resetTodoList(fafPath);
            return;
        }
        if (options.show) {
            await showCurrentTodoList(fafPath);
            return;
        }
        // Generate new improvement plan
        await generateImprovementPlan(fafPath);
        const duration = Date.now() - startTime;
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafGreen(`${championship_style_1.FAF_ICONS.trophy} Improvement plan ready in ${duration}ms!`));
        console.log(`${championship_style_1.FAF_COLORS.fafCyan(`${championship_style_1.FAF_ICONS.magic_wand} Try: `)}faf todo --show${championship_style_1.FAF_COLORS.fafCyan(' - View your todo list')}`);
    }
    catch (error) {
        console.error(championship_style_1.FAF_COLORS.fafOrange(`${championship_style_1.FAF_ICONS.shield} Improvement failed: ${error instanceof Error ? error.message : String(error)}`));
        process.exit(1);
    }
}
/**
 * Generate new improvement plan based on current score
 */
async function generateImprovementPlan(fafPath) {
    // Calculate current score and context
    const compiler = new faf_compiler_1.FafCompiler();
    const scoreResult = await compiler.compile(fafPath);
    const projectDir = path.dirname(fafPath);
    // Get existing files for context
    const existingFiles = await getProjectFiles(projectDir);
    // Read .faf for missing context analysis
    const fafContent = await fs.readFile(fafPath, 'utf-8');
    const fafData = (0, yaml_1.parse)(fafContent) || {};
    const missingSlots = identifyMissingSlots(fafData, existingFiles);
    // Create todo engine and generate plan
    const engine = (0, claude_todo_engine_1.createClaudeTodoEngine)();
    const todoList = engine.generateTodoList({
        currentScore: scoreResult.score || 0,
        projectType: fafData.project?.name || 'unknown',
        missingSlots,
        existingFiles,
        techStack: fafData.stack || {},
        aiPreference: 'claude' // Default to Claude-style tasks
    });
    // Save todo list
    await saveTodoList(todoList, fafPath);
    // Display the plan
    displayTodoList(todoList);
}
/**
 * Display todo list in championship style
 */
function displayTodoList(todoList) {
    const engine = (0, claude_todo_engine_1.createClaudeTodoEngine)();
    const progress = engine.getProgress(todoList);
    console.log();
    console.log(`┌─────────────────────────────────────────┐`);
    console.log(`│ ${championship_style_1.FAF_COLORS.fafCyan('🤖 Claude-Inspired Improvement Plan')}     │`);
    console.log(`│ ${championship_style_1.FAF_COLORS.fafOrange(`Current: ${todoList.currentScore}%`)} → ${championship_style_1.FAF_COLORS.fafGreen(`Target: ${todoList.targetScore}%`)}        │`);
    console.log(`└─────────────────────────────────────────┘`);
    console.log();
    console.log(championship_style_1.FAF_COLORS.fafCyan('📝 Your Championship Todo List:'));
    todoList.items.forEach((item, index) => {
        const connector = index === todoList.items.length - 1 ? '└─' : '├─';
        const checkbox = item.completed ? '☑️' : '[ ]';
        const impactColor = item.impact >= 15 ? championship_style_1.FAF_COLORS.fafGreen :
            item.impact >= 10 ? championship_style_1.FAF_COLORS.fafOrange : championship_style_1.FAF_COLORS.fafCyan;
        const highImpact = item.impact >= 15 ? ' 💯 HIGH IMPACT' : '';
        console.log(`${championship_style_1.FAF_COLORS.fafCyan(`${connector} `)}${checkbox} ${item.title} ${impactColor(`(+${item.impact} points)`)}${highImpact}`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('   ')}${championship_style_1.FAF_COLORS.fafCyan(`~ ${item.estimatedMinutes}min · ${item.description}`)}`);
    });
    console.log();
    console.log(`🏆 Complete all tasks → ${championship_style_1.FAF_COLORS.fafGreen(`${todoList.targetScore}% score!`)} Championship ready!`);
    console.log();
    console.log(championship_style_1.FAF_COLORS.fafCyan('💡 Complete tasks with: ') + championship_style_1.FAF_COLORS.fafOrange('faf todo --complete <task-number>'));
}
/**
 * Show current todo list if it exists
 */
async function showCurrentTodoList(fafPath) {
    const todoList = await loadTodoList(fafPath);
    if (!todoList) {
        console.log(`${championship_style_1.FAF_COLORS.fafOrange('└─ ')}No active improvement plan. Run ${championship_style_1.FAF_COLORS.fafCyan('faf todo')} to create one.`);
        return;
    }
    const engine = (0, claude_todo_engine_1.createClaudeTodoEngine)();
    const progress = engine.getProgress(todoList);
    console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}Current Progress: ${claude_todo_engine_1.TodoEngineUtils.formatProgressCLI(progress)}`);
    console.log();
    displayTodoList(todoList);
}
/**
 * Complete a specific task
 */
async function completeTask(taskIdentifier, fafPath) {
    const todoList = await loadTodoList(fafPath);
    if (!todoList) {
        console.log(`${championship_style_1.FAF_COLORS.fafOrange('└─ ')}No active todo list. Run ${championship_style_1.FAF_COLORS.fafCyan('faf todo')} first.`);
        return;
    }
    // Parse task identifier (could be number or partial title)
    const taskIndex = parseInt(taskIdentifier) - 1; // 1-based indexing for users
    let task;
    if (!isNaN(taskIndex) && taskIndex >= 0 && taskIndex < todoList.items.length) {
        task = todoList.items[taskIndex];
    }
    else {
        // Try to find by partial title match (convert to string first)
        const identifier = String(taskIdentifier);
        task = todoList.items.find(item => item.title.toLowerCase().includes(identifier.toLowerCase()));
    }
    if (!task) {
        console.log(`${championship_style_1.FAF_COLORS.fafOrange('└─ ')}Task "${taskIdentifier}" not found. Use ${championship_style_1.FAF_COLORS.fafCyan('faf todo --show')} to see available tasks.`);
        return;
    }
    if (task.completed) {
        console.log(`${championship_style_1.FAF_COLORS.fafOrange('└─ ')}Task "${task.title}" is already completed! 🎉`);
        return;
    }
    // Recalculate score to get new project score
    const compiler = new faf_compiler_1.FafCompiler();
    const scoreResult = await compiler.compile(fafPath);
    // Complete the task
    const engine = (0, claude_todo_engine_1.createClaudeTodoEngine)();
    const improvement = engine.completeTask(todoList, task.id, scoreResult.score || 0);
    // Save updated todo list
    await saveTodoList(todoList, fafPath);
    // Celebrate!
    console.log();
    console.log(claude_todo_engine_1.TodoEngineUtils.generateCelebration(improvement));
    console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}Task completed: ${task.title}`);
    console.log(`${championship_style_1.FAF_COLORS.fafCyan('└─ ')}Score improvement: ${improvement.before}% → ${improvement.after}%`);
    // Check for championship completion
    if (improvement.celebrationLevel === 'championship') {
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafGreen('🎊 CHAMPIONSHIP ACHIEVED! 🏁'));
        console.log(championship_style_1.FAF_COLORS.fafGreen('🏆 Your AI context is now maximally optimized!'));
        console.log(championship_style_1.FAF_COLORS.fafCyan('💎 Technical Credit: +25 points (Perfect Score Bonus)'));
    }
}
/**
 * Reset todo list
 */
async function resetTodoList(fafPath) {
    const todoPath = getTodoListPath(fafPath);
    if (await (0, file_utils_1.fileExists)(todoPath)) {
        await fs.unlink(todoPath);
        console.log(`${championship_style_1.FAF_COLORS.fafGreen('└─ ')}Todo list reset! Run ${championship_style_1.FAF_COLORS.fafCyan('faf todo')} to create a new one.`);
    }
    else {
        console.log(`${championship_style_1.FAF_COLORS.fafOrange('└─ ')}No todo list to reset.`);
    }
}
// =====================================
// HELPER FUNCTIONS
// =====================================
function getTodoListPath(fafPath) {
    const projectDir = path.dirname(fafPath);
    return path.join(projectDir, '.faf-todos.json');
}
async function saveTodoList(todoList, fafPath) {
    const todoPath = getTodoListPath(fafPath);
    await fs.writeFile(todoPath, JSON.stringify(todoList, null, 2));
}
async function loadTodoList(fafPath) {
    const todoPath = getTodoListPath(fafPath);
    if (!(await (0, file_utils_1.fileExists)(todoPath))) {
        return null;
    }
    try {
        const content = await fs.readFile(todoPath, 'utf-8');
        const data = JSON.parse(content);
        // Convert date strings back to Date objects
        data.createdAt = new Date(data.createdAt);
        data.updatedAt = new Date(data.updatedAt);
        if (data.completedAt) {
            data.completedAt = new Date(data.completedAt);
        }
        data.items.forEach((item) => {
            if (item.completedAt) {
                item.completedAt = new Date(item.completedAt);
            }
        });
        return data;
    }
    catch {
        return null;
    }
}
async function getProjectFiles(projectDir) {
    try {
        const files = await fs.readdir(projectDir);
        return files.filter(file => !file.startsWith('.') || file === '.gitignore');
    }
    catch {
        return [];
    }
}
function identifyMissingSlots(fafData, existingFiles) {
    const missing = [];
    if (!fafData.project?.goal) {
        missing.push('project_goals');
    }
    if (!fafData.project?.description) {
        missing.push('project_description');
    }
    if (!existingFiles.includes('README.md')) {
        missing.push('readme');
    }
    if (!fafData.stack || Object.keys(fafData.stack).length === 0) {
        missing.push('tech_stack');
    }
    if (!fafData.human_context) {
        missing.push('human_context');
    }
    return missing;
}
//# sourceMappingURL=todo.js.map