#!/bin/bash
# Simplified vault sync utility
# Purpose: Quick git operations for vault/notes repository

set -euo pipefail  # Exit on error, undefined vars, pipe failures

# Configuration
readonly REPO_DIR="${HOME}/repos/vault"

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

# Logging functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $*"
}

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

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

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

# Enhanced git operations
gitops() {
    log_info "Checking vault repository status..."
    
    if [[ ! -d "$REPO_DIR" ]]; then
        log_error "Vault directory does not exist: $REPO_DIR"
        return 1
    fi
    
    cd "$REPO_DIR" || {
        log_error "Failed to change to vault directory"
        return 1
    }
    
    if [[ ! -d ".git" ]]; then
        log_error "Not a git repository: $REPO_DIR"
        return 1
    fi
    
    if [[ -z "$(git status --porcelain)" ]]; then
        log_info "No changes detected in vault"
        return 0
    fi
    
    log_info "Changes detected in vault:"
    git status --short
    
    echo
    read -p "Continue with committing? (Y/n) >> " confirm
    if [[ "$confirm" =~ ^[nN]([oO])?$ ]]; then
        log_info "Commit cancelled by user"
        return 0
    fi
    
    read -p "Commit message (leave empty for automatic) >> " commit_message
    if [[ -z "$commit_message" ]]; then
        commit_message="auto sync $(date '+%Y-%m-%d %H:%M')"
    fi
    
    git add -A
    git commit -m "$commit_message"
    log_success "Changes committed: $commit_message"
    
    echo
    read -p "Continue with pushing? (Y/n) >> " confirm
    if [[ "$confirm" =~ ^[nN]([oO])?$ ]]; then
        log_info "Push cancelled by user"
        return 0
    fi
    
    git push origin main
    log_success "Changes pushed to remote repository"
}

# Show usage information
show_usage() {
    cat << EOF
Simplified Vault Sync Utility

Usage: $0 [OPTIONS]

Options:
    -h, --help       Show this help message
    -s, --status     Show git status only (no operations)
    -q, --quick      Quick commit with auto message (no prompts)
    -m, --message    Specify commit message directly

Examples:
    $0               # Interactive sync with prompts
    $0 --status      # Just show current status
    $0 --quick       # Quick auto-commit and push
    $0 -m "Updated daily notes"  # Commit with specific message
EOF
}

# Quick commit function (no prompts)
quick_commit() {
    local commit_message="$1"
    
    cd "$REPO_DIR" || {
        log_error "Failed to change to vault directory"
        return 1
    }
    
    if [[ -z "$(git status --porcelain)" ]]; then
        log_info "No changes detected in vault"
        return 0
    fi
    
    if [[ -z "$commit_message" ]]; then
        commit_message="auto sync $(date '+%Y-%m-%d %H:%M')"
    fi
    
    git add -A
    git commit -m "$commit_message"
    log_success "Changes committed: $commit_message"
    
    git push origin main
    log_success "Changes pushed to remote repository"
}

# Show status only
show_status() {
    cd "$REPO_DIR" || {
        log_error "Failed to change to vault directory"
        return 1
    }
    
    if [[ -z "$(git status --porcelain)" ]]; then
        log_info "Vault is clean - no changes detected"
    else
        log_info "Changes in vault:"
        git status --short
        echo
        git status
    fi
}

# Validation function
validate_environment() {
    local errors=0
    
    if [[ ! -d "$REPO_DIR" ]]; then
        log_error "Vault directory does not exist: $REPO_DIR"
        ((errors++))
    fi
    
    if ! command -v git &> /dev/null; then
        log_error "git is required but not installed"
        ((errors++))
    fi
    
    return $errors
}

# Main function
main() {
    local quick_mode=false
    local status_only=false
    local commit_message=""
    
    # Parse command line arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_usage
                exit 0
                ;;
            -s|--status)
                status_only=true
                shift
                ;;
            -q|--quick)
                quick_mode=true
            E    shift
                ;;
            -m|--message)
                if [[ -z "$2" ]]; then
                    log_error "--message requires a commit message argument"
                    exit 1
                fi
                commit_message="$2"
                quick_mode=true
                shift 2
                ;;
            *)
                log_error "Unknown option: $1"
                show_usage
                exit 1
                ;;
        esac
    done
    
    # Validate environment
    if ! validate_environment; then
        log_error "Environment validation failed"
        exit 1
    fi

    # sync scripts with the vault 
    local scripts_dir=${REPO_DIR}/content/scripts
    rm ${scripts_dir}/*

    cp ${HOME}/repos/dotfiles-snippets/setup-desktop/setup-desktop ${scripts_dir}
    cp ${HOME}/repos/dotfiles-snippets/setup-nvim/setup-nvim ${scripts_dir}
    cp ${HOME}/repos/dotfiles-snippets/sync-dotfiles/sync-dotfiles ${scripts_dir}
    cp ${HOME}/repos/vault-snippets/sync-vault/sync-vault ${scripts_dir}
    cp ${HOME}/scripts/android-screen ${scripts_dir}
    
    # Execute based on mode
    if [[ "$status_only" == true ]]; then
        show_status
    elif [[ "$quick_mode" == true ]]; then
        log_info "Quick sync mode..."
        quick_commit "$commit_message"
    else
        log_info "Interactive sync mode..."
        gitops
    fi
    
    log_success "Vault sync completed!"
}

# Run main function with all arguments
main "$@"
