/**
 * Todo Stats - Statistics and queries
 */

import type { Todo, TodoStats } from "../../shared/loop/types.js";
import { TODO_STATUS, STATUS_LABEL } from "../../shared/index.js";

/**
 * Get count of incomplete todos
 */
export function getIncompleteCount(todos: Todo[]): number {
    return todos.filter(t =>
        t.status !== TODO_STATUS.COMPLETED &&
        t.status !== TODO_STATUS.CANCELLED
    ).length;
}

/**
 * Check if there's remaining work
 */
export function hasRemainingWork(todos: Todo[]): boolean {
    return getIncompleteCount(todos) > 0;
}

/**
 * Get next pending todo (highest priority first)
 */
export function getNextPending(todos: Todo[]): Todo | undefined {
    const pending = todos.filter(t =>
        t.status === TODO_STATUS.PENDING || t.status === TODO_STATUS.IN_PROGRESS
    );

    // Sort by priority: high > medium > low
    const priorityOrder = {
        [STATUS_LABEL.HIGH]: 0,
        [STATUS_LABEL.MEDIUM]: 1,
        [STATUS_LABEL.LOW]: 2
    };
    pending.sort((a, b) => priorityOrder[a.priority] - priorityOrder[b.priority]);

    return pending[0];
}

/**
 * Calculate todo statistics
 */
export function getStats(todos: Todo[]): TodoStats {
    const stats = {
        total: todos.length,
        pending: todos.filter(t => t.status === TODO_STATUS.PENDING).length,
        inProgress: todos.filter(t => t.status === TODO_STATUS.IN_PROGRESS).length,
        completed: todos.filter(t => t.status === TODO_STATUS.COMPLETED).length,
        cancelled: todos.filter(t => t.status === TODO_STATUS.CANCELLED).length,
        percentComplete: 0,
    };

    if (stats.total > 0) {
        stats.percentComplete = Math.round(
            ((stats.completed + stats.cancelled) / stats.total) * 100
        );
    }

    return stats;
}

/**
 * Check if mission is complete based on todos
 */
export function isMissionComplete(todos: Todo[]): boolean {
    if (todos.length === 0) {
        return false; // No todos means we don't know completion status
    }

    return !hasRemainingWork(todos);
}
