#!/bin/bash

################################################################################
# timestamp-docs.sh - Prefix .md files with creation timestamps
################################################################################
#
# Purpose: Add YYYYMMDD-HHMM_ prefix to all .md files in docs directories
#          to help identify and filter old documentation
#
# Usage:
#   ./timestamp-docs.sh [OPTIONS]
#
# Options:
#   --dry-run              Preview changes without renaming (default)
#   --execute              Actually rename the files
#   --dir=PATH             Process specific directory (default: both repos)
#   --backend-only         Process only backend repo docs
#   --frontend-only        Process only frontend repo docs
#   -h, --help             Show this help message
#
# Examples:
#   ./timestamp-docs.sh --dry-run              # Preview all changes
#   ./timestamp-docs.sh --execute              # Rename all files
#   ./timestamp-docs.sh --backend-only         # Backend only (dry-run)
#   ./timestamp-docs.sh --execute --dir=/path  # Specific directory
#
################################################################################

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Default configuration
DRY_RUN=true
BACKEND_REPO="/Users/charlie/code/showprima/docs"
FRONTEND_REPO="/Users/charlie/code/showprima-frontend/docs"
CUSTOM_DIR=""
BACKEND_ONLY=false
FRONTEND_ONLY=false

# Statistics
TOTAL_FILES=0
RENAMED_FILES=0
SKIPPED_FILES=0
ERROR_FILES=0

################################################################################
# Functions
################################################################################

show_help() {
    cat << EOF
${BLUE}timestamp-docs.sh${NC} - Prefix .md files with creation timestamps

${YELLOW}Usage:${NC}
  ./timestamp-docs.sh [OPTIONS]

${YELLOW}Options:${NC}
  ${GREEN}--dry-run${NC}              Preview changes without renaming (default)
  ${GREEN}--execute${NC}              Actually rename the files
  ${GREEN}--dir=PATH${NC}             Process specific directory
  ${GREEN}--backend-only${NC}         Process only backend repo docs
  ${GREEN}--frontend-only${NC}        Process only frontend repo docs
  ${GREEN}-h, --help${NC}             Show this help message

${YELLOW}Examples:${NC}
  ./timestamp-docs.sh --dry-run              # Preview all changes
  ./timestamp-docs.sh --execute              # Rename all files in both repos
  ./timestamp-docs.sh --execute --backend-only   # Backend repo only
  ./timestamp-docs.sh --dir=/path/to/docs    # Specific directory (dry-run)

${YELLOW}Timestamp Format:${NC}
  YYYYMMDD-HHMM_{filename}.md

  Example: 20251024-1430_BOOKING_FLOW_DIAGNOSTIC.md

${YELLOW}Notes:${NC}
  - Uses file creation time (birth time) for timestamp
  - Skips files that already have timestamp prefixes
  - Skips CLAUDE*.md files (reference documentation)
  - Skips README.md files (repository documentation)
  - Handles nested directories recursively
  - Preserves original files in dry-run mode

EOF
    exit 0
}

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if file should be ignored
should_ignore_file() {
    local filename="$1"

    # Ignore CLAUDE*.md files (e.g., CLAUDE.md, CLAUDE_INTEGRATED.md)
    if [[ "$filename" =~ ^CLAUDE.*\.md$ ]]; then
        return 0  # true (should ignore)
    fi

    # Ignore README.md files
    if [[ "$filename" == "README.md" ]]; then
        return 0  # true (should ignore)
    fi

    return 1  # false (don't ignore)
}

# Check if file already has timestamp prefix
has_timestamp_prefix() {
    local filename="$1"
    # Match pattern: YYYYMMDD-HHMM_
    if [[ "$filename" =~ ^[0-9]{8}-[0-9]{4}_ ]]; then
        return 0  # true
    else
        return 1  # false
    fi
}

# Get file creation timestamp
get_file_timestamp() {
    local filepath="$1"

    # Get file birth time (creation time) on macOS
    local birth_time=$(stat -f "%B" "$filepath" 2>/dev/null)

    if [ -z "$birth_time" ]; then
        log_error "Failed to get creation time for: $filepath"
        return 1
    fi

    # Format as YYYYMMDD-HHMM
    local timestamp=$(date -r "$birth_time" "+%Y%m%d-%H%M" 2>/dev/null)

    if [ -z "$timestamp" ]; then
        log_error "Failed to format timestamp for: $filepath"
        return 1
    fi

    echo "$timestamp"
}

# Process a single file
process_file() {
    local filepath="$1"
    local filename=$(basename "$filepath")
    local dirname=$(dirname "$filepath")

    TOTAL_FILES=$((TOTAL_FILES + 1))

    # Skip if file should be ignored (CLAUDE*.md, README.md)
    if should_ignore_file "$filename"; then
        log_warning "Skipped (ignored file): $filename"
        SKIPPED_FILES=$((SKIPPED_FILES + 1))
        return 0
    fi

    # Skip if already has timestamp prefix
    if has_timestamp_prefix "$filename"; then
        log_warning "Skipped (already has timestamp): $filename"
        SKIPPED_FILES=$((SKIPPED_FILES + 1))
        return 0
    fi

    # Get file creation timestamp
    local timestamp=$(get_file_timestamp "$filepath")
    if [ $? -ne 0 ]; then
        ERROR_FILES=$((ERROR_FILES + 1))
        return 1
    fi

    # Generate new filename
    local new_filename="${timestamp}_${filename}"
    local new_filepath="${dirname}/${new_filename}"

    # Check if target already exists
    if [ -f "$new_filepath" ]; then
        log_error "Target already exists: $new_filepath"
        ERROR_FILES=$((ERROR_FILES + 1))
        return 1
    fi

    # Rename or preview
    if [ "$DRY_RUN" = true ]; then
        echo -e "  ${YELLOW}WOULD RENAME:${NC}"
        echo -e "    ${RED}FROM:${NC} $filename"
        echo -e "    ${GREEN}TO:${NC}   $new_filename"
    else
        mv "$filepath" "$new_filepath"
        if [ $? -eq 0 ]; then
            log_success "Renamed: $filename → $new_filename"
        else
            log_error "Failed to rename: $filename"
            ERROR_FILES=$((ERROR_FILES + 1))
            return 1
        fi
    fi

    RENAMED_FILES=$((RENAMED_FILES + 1))
    return 0
}

# Process directory recursively
process_directory() {
    local dir="$1"
    local label="$2"

    if [ ! -d "$dir" ]; then
        log_error "Directory not found: $dir"
        return 1
    fi

    log_info "Processing: $label ($dir)"
    echo ""

    # Find all .md files recursively
    while IFS= read -r -d '' file; do
        process_file "$file"
    done < <(find "$dir" -type f -name "*.md" -print0 | sort -z)

    echo ""
}

# Show statistics
show_statistics() {
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo -e "${BLUE}Statistics:${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo -e "  Total files found:       ${BLUE}${TOTAL_FILES}${NC}"
    echo -e "  Files renamed:           ${GREEN}${RENAMED_FILES}${NC}"
    echo -e "  Files skipped:           ${YELLOW}${SKIPPED_FILES}${NC}"
    echo -e "  Errors:                  ${RED}${ERROR_FILES}${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    if [ "$DRY_RUN" = true ]; then
        echo ""
        log_warning "DRY RUN MODE - No files were actually renamed"
        echo -e "  Run with ${GREEN}--execute${NC} to perform the renaming"
    fi

    echo ""
}

################################################################################
# Main Script
################################################################################

# Parse command line arguments
for arg in "$@"; do
    case $arg in
        --dry-run)
            DRY_RUN=true
            ;;
        --execute)
            DRY_RUN=false
            ;;
        --dir=*)
            CUSTOM_DIR="${arg#*=}"
            ;;
        --backend-only)
            BACKEND_ONLY=true
            ;;
        --frontend-only)
            FRONTEND_ONLY=true
            ;;
        -h|--help)
            show_help
            ;;
        *)
            log_error "Unknown option: $arg"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Show header
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "${BLUE}Documentation Timestamp Utility${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ "$DRY_RUN" = true ]; then
    log_warning "Running in DRY RUN mode (no files will be renamed)"
else
    log_info "Running in EXECUTE mode (files WILL be renamed)"
fi

echo ""

# Process directories based on options
if [ -n "$CUSTOM_DIR" ]; then
    # Custom directory specified
    process_directory "$CUSTOM_DIR" "Custom Directory"
elif [ "$BACKEND_ONLY" = true ]; then
    # Backend only
    process_directory "$BACKEND_REPO" "Backend Repository"
elif [ "$FRONTEND_ONLY" = true ]; then
    # Frontend only
    process_directory "$FRONTEND_REPO" "Frontend Repository"
else
    # Both repositories (default)
    process_directory "$BACKEND_REPO" "Backend Repository"
    process_directory "$FRONTEND_REPO" "Frontend Repository"
fi

# Show statistics
show_statistics

# Exit with appropriate code
if [ $ERROR_FILES -gt 0 ]; then
    exit 1
else
    exit 0
fi
