#!/bin/bash

# Two-Way Sync Script for Starting Line Productions LLC Website
# This script helps sync changes between local git and production server
#
# Usage: ./sync.sh [direction]
# Directions:
#   down   - Pull changes from production (after non-technical users edit via admin)
#   up     - Push local changes to production (after technical/AI edits)
#   status  - Check sync status between local and remote

set -e

# Configuration
REMOTE_HOST="your-production-server.com"
REMOTE_PATH="/path/to/grav/config/www"
LOCAL_PATH="/home/charles/Projects/STLPWebsite/config/www"

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

# Helper functions
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"
}

# Function: Check for local changes
check_local_changes() {
    if [ -n "$(git status --porcelain)" ]; then
        return 0
    else
        return 1
    fi
}

# Function: Check for unpushed commits
check_unpushed() {
    local unpushed=$(git rev-list --count HEAD@{u}..HEAD 2>/dev/null || echo "0")
    if [ "$unpushed" -gt 0 ]; then
        return 0
    else
        return 1
    fi
}

# Function: Clear Grav cache
clear_cache() {
    log_info "Clearing Grav cache..."
    docker exec stlp-grav rm -rf /config/www/user/cache/*
    log_success "Cache cleared"
}

# Function: Show sync status
show_status() {
    log_info "Checking sync status..."

    echo ""
    echo "=== Git Status ==="
    if check_local_changes; then
        log_warning "You have uncommitted changes:"
        git status --short
    else
        log_success "No uncommitted changes"
    fi

    echo ""
    echo "=== Remote Sync Status ==="
    if check_unpushed; then
        local unpushed=$(git rev-list --count HEAD@{u}..HEAD)
        log_warning "You have $unpushed unpushed commit(s)"
    else
        log_success "All commits are pushed to remote"
    fi

    echo ""
    echo "=== Recent Admin Edits ==="
    if [ -f ".last_admin_sync" ]; then
        log_info "Last admin sync: $(cat .last_admin_sync)"
    else
        log_warning "No admin sync recorded"
    fi
}

# Function: Sync down from production (after admin edits)
sync_down() {
    log_info "Starting SYNC DOWN (Production → Local)..."
    echo ""

    # Check if there are local uncommitted changes
    if check_local_changes; then
        log_error "You have uncommitted local changes!"
        echo ""
        log_warning "Please commit or stash your changes before syncing down from production."
        log_info "Use 'git stash' to save changes temporarily."
        log_info "Use 'git commit' to commit changes first."
        exit 1
    fi

    # Pull latest from remote (production should push to remote)
    log_info "Pulling latest changes from remote repository..."
    git pull origin main

    # Check what changed
    log_info "Checking what changed..."
    if git diff HEAD@{1} HEAD --stat | grep -q "user/pages"; then
        log_warning "Pages were modified (likely by admin UI)"
    fi
    if git diff HEAD@{1} HEAD --stat | grep -q "user/config"; then
        log_warning "Config was modified (likely by admin UI)"
    fi

    # Clear cache
    clear_cache

    # Record sync
    date > .last_admin_sync

    log_success "Sync down complete!"
    echo ""
    log_info "Production changes are now available locally."
    log_info "You can continue working on these files."
}

# Function: Sync up to production (after local/AI edits)
sync_up() {
    log_info "Starting SYNC UP (Local → Production)..."
    echo ""

    # Check if there are uncommitted changes
    if check_local_changes; then
        log_error "You have uncommitted changes!"
        echo ""
        log_info "Please commit your changes before syncing up."
        log_info "Use 'git commit' to save your changes."
        exit 1
    fi

    # Check if there are unpushed commits
    if ! check_unpushed; then
        log_warning "No commits to push!"
        log_info "Make changes and commit them first."
        exit 0
    fi

    # Check if there are new commits on remote (admin might have edited)
    log_info "Checking for remote changes..."
    git fetch origin
    local unpushed_local=$(git rev-list --count HEAD@{u}..HEAD)
    local unpushed_remote=$(git rev-list --count HEAD..HEAD@{u})

    if [ "$unpushed_remote" -gt 0 ]; then
        log_error "There are $unpushed_remote new commit(s) on remote!"
        echo ""
        log_warning "This means someone (likely via admin UI) has edited content on production."
        log_info "Please sync down first to merge those changes:"
        log_info "  $ ./sync.sh down"
        log_info ""
        log_info "Then resolve any conflicts before syncing up."
        exit 1
    fi

    # Show what will be pushed
    log_info "Commits to be pushed:"
    git log --oneline origin/main..HEAD

    echo ""
    log_info "Pushing changes to remote..."
    git push origin main

    log_success "Sync up complete!"
    echo ""
    log_info "Local changes have been pushed to production."
    log_warning "Production will pull these changes automatically (via webhook or manual pull)."
}

# Function: Test local site
test_site() {
    log_info "Testing local site..."
    clear_cache
    log_success "Cache cleared, restart container if needed"
    log_info "Visit: http://localhost:5001"
}

# Function: Show help
show_help() {
    cat << EOF
Two-Way Sync Script for Starting Line Productions LLC Website

Usage: ./sync.sh [command]

Commands:
    down     Sync DOWN from production (use after admin UI edits)
    up       Sync UP to production (use after local/AI edits)
    status   Show sync status between local and remote
    test     Clear cache and test local site
    help     Show this help message

Workflow:
    1. Non-technical users edit content via admin UI on production
    2. Production changes are pushed to git remote
    3. Technical users run: ./sync.sh down
    4. Resolve any conflicts if needed
    5. Technical users edit content via markdown/git
    6. Run: ./sync.sh up
    7. Production pulls changes from git remote

Tips:
    - Always run 'status' before syncing to see current state
    - Commit your changes before syncing up
    - Pull changes before syncing down
    - Check for conflicts and resolve them promptly
    - Test locally after syncing down

Examples:
    ./sync.sh status    # Check sync status
    ./sync.sh down      # Pull production changes
    ./sync.sh up        # Push local changes
    ./sync.sh test       # Test local site

For detailed workflow documentation, see: AGENTS.md

EOF
}

# Main script logic
case "${1:-}" in
    down)
        sync_down
        ;;
    up)
        sync_up
        ;;
    status)
        show_status
        ;;
    test)
        test_site
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        log_error "Unknown command: ${1:-}"
        echo ""
        show_help
        exit 1
        ;;
esac
