#!/bin/bash
#
# Todo.sh Format Action - Comprehensive formatting for todo.txt files
#
# Usage: todo.sh format [options]
#
# This action provides a clean interface to the todo.txt formatter,
# supporting both comprehensive and simple formatting modes.
#

set -euo pipefail

# Action description for todo.sh help system
ACTION="format"
if [[ "${1:-}" == "usage" ]]; then
    echo "    format [OPTIONS]:"
    echo "        Format and normalize todo.txt and done.txt files"
    echo "        OPTIONS:"
    echo "          --simple       Use simple formatter (faster, fewer features)"
    echo "          --dry-run|-n   Preview changes without applying them"
    echo "          --verbose|-v   Show detailed processing information"
    echo "          --quiet|-q     Suppress non-essential output"
    echo "          --check-only   Validate and report without making changes"
    echo "          --help|-h      Show detailed help"
    echo ""
    exit 0
fi

# Skip the action name argument if it was passed by todo.sh
if [[ "${1:-}" == "format" ]]; then
    shift
fi

# Get the directory where this script resides (should be ~/.todo.actions.d)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
RESET='\033[0m'

echo_info() { echo -e "${GREEN}INFO:${RESET} $*" >&2; }
echo_warning() { echo -e "${YELLOW}WARNING:${RESET} $*" >&2; }
echo_error() { echo -e "${RED}ERROR:${RESET} $*" >&2; }

# Show detailed help
show_help() {
    cat << 'EOF'
Todo.sh Format Action - Comprehensive formatting for todo.txt files

USAGE:
    todo.sh format [OPTIONS]

DESCRIPTION:
    Formats and normalizes your todo.txt and done.txt files according to the
    official specification. Uses a robust Go-based formatter when available,
    with fallback to bash-based formatters. Fixes common issues like priority
    placement, date formats, context/project positioning, and metadata spacing.

OPTIONS:
    --simple            Use simple formatter (faster, fewer features)
    --dry-run, -n       Preview changes without applying them  
    --verbose, -v       Show detailed processing information
    --quiet, -q         Suppress non-essential output
    --check-only        Validate and report without making changes
    --help, -h          Show this help message

FORMATTING FEATURES:
    ✓ Priority validation and placement: (A) at start of line
    ✓ Date normalization: YYYY-MM-DD format for all dates
    ✓ Context (@) and project (+) repositioning after description
    ✓ Metadata spacing: key:value format standardization  
    ✓ Completed task validation: proper x YYYY-MM-DD format
    ✓ Comment and blank line preservation
    ✓ Section-based sorting (comprehensive mode)
    ✓ Atomic file updates with timestamped backups
    ✓ File locking to prevent concurrent modifications (comprehensive mode)

MODES:
    Comprehensive (default): Full-featured formatter with advanced validation,
                           section-aware sorting, and comprehensive statistics.
                           
    Simple (--simple):     Lightweight formatter focusing on the most common
                           formatting issues. Faster but fewer features.

EXAMPLES:
    todo.sh format                    # Format using comprehensive mode
    todo.sh format --simple           # Use simple formatter  
    todo.sh format --dry-run          # Preview changes
    todo.sh format --simple -n        # Simple dry-run
    todo.sh format --verbose          # Detailed output
    todo.sh format --check-only       # Validate without changes

EXIT CODES:
    0    Success: Files processed and updated (or confirmed clean)
    1    Error: Processing failed, files not updated  
    2    Check mode: Issues found but no changes made

SPECIFICATION:
    Follows the official todo.txt specification:
    https://github.com/todotxt/todo.txt

EOF
}

# Parse arguments
USE_SIMPLE=false
FORMATTER_ARGS=()

while [[ $# -gt 0 ]]; do
    case $1 in
        --simple)
            USE_SIMPLE=true
            shift
            ;;
        --dry-run|-n)
            FORMATTER_ARGS+=("--dry-run")
            shift
            ;;
        --verbose|-v)
            FORMATTER_ARGS+=("--verbose")
            shift
            ;;
        --quiet|-q)
            FORMATTER_ARGS+=("--quiet")
            shift
            ;;
        --check-only)
            FORMATTER_ARGS+=("--check-only")
            shift
            ;;
        --help|-h)
            show_help
            exit 0
            ;;
        *)
            echo_error "Unknown option: $1"
            echo "Use 'todo.sh format --help' for usage information."
            exit 1
            ;;
    esac
done

# Determine which formatter to use and build command
# Look for Go formatter in bin directory relative to dotfiles
DOTFILES_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
GO_FORMATTER="$DOTFILES_DIR/bin/todotxtfmt/todotxtfmt"

if [[ $USE_SIMPLE == true ]]; then
    echo_error "Simple formatter has been deprecated. Use --dry-run for preview mode instead."
    echo_error "Run: todo.sh format --dry-run"
    exit 1
elif [[ -x "$GO_FORMATTER" ]]; then
    # Use Go-based formatter (now the only option)
    FORMATTER_CMD="$GO_FORMATTER"

    # Add arguments compatible with Go formatter
    for arg in "${FORMATTER_ARGS[@]:-}"; do
        case "$arg" in
            --dry-run) FORMATTER_CMD="$FORMATTER_CMD --dry-run" ;;
            --verbose) FORMATTER_CMD="$FORMATTER_CMD --verbose" ;;
            --quiet) FORMATTER_CMD="$FORMATTER_CMD --quiet" ;;
            --check-only) FORMATTER_CMD="$FORMATTER_CMD --dry-run --diff" ;;
        esac
    done

    # Go formatter uses environment variables automatically
    # No need to explicitly pass TODO_FILE
else
    echo_error "Go formatter not found at: $GO_FORMATTER"
    echo_error "Make sure the todotxtfmt binary is built and available."
    echo_error "Run: cd '$DOTFILES_DIR/bin/todotxtfmt' && go build -o todotxtfmt cmd/todotxtfmt/main.go"
    exit 1
fi

# Check that the Go formatter exists
if [[ ! -x "$GO_FORMATTER" ]]; then
    echo_error "Go formatter not found or not executable: $GO_FORMATTER"
    echo_error "Build it with: cd '$DOTFILES_DIR/bin/todotxtfmt' && go build -o todotxtfmt cmd/todotxtfmt/main.go"
    exit 1
fi

# Inform user which formatter is being used
echo_info "Using Go-based formatter"

# Execute the formatter
eval "$FORMATTER_CMD"