#!/bin/bash
################################################################################
# Media Downloader Version Update Script
# Updates version numbers across all application files
# Usage: bash scripts/update-version.sh 6.4.3
################################################################################

set -e  # Exit on error

NEW_VERSION="$1"
OLD_VERSION=$(cat /opt/media-downloader/VERSION 2>/dev/null || echo "unknown")

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

# Function to print colored output
print_success() { echo -e "${GREEN}✓${NC} $1"; }
print_error() { echo -e "${RED}✗${NC} $1"; }
print_info() { echo -e "${BLUE}ℹ${NC} $1"; }
print_warning() { echo -e "${YELLOW}⚠${NC} $1"; }

################################################################################
# Validate Input
################################################################################

if [ -z "$NEW_VERSION" ]; then
    print_error "No version specified!"
    echo ""
    echo "Usage: $0 <version>"
    echo "Example: $0 6.4.3"
    echo ""
    exit 1
fi

# Validate version format (X.X.X)
if ! [[ "$NEW_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    print_error "Invalid version format: $NEW_VERSION"
    echo "Version must be in format X.X.X (e.g., 6.4.3)"
    exit 1
fi

################################################################################
# Header
################################################################################

echo ""
echo "╔════════════════════════════════════════════════╗"
echo "║   Media Downloader Version Update             ║"
echo "╠════════════════════════════════════════════════╣"
echo "║ Current: ${OLD_VERSION}                       "
echo "║ New:     ${NEW_VERSION}                       "
echo "╚════════════════════════════════════════════════╝"
echo ""

# Confirm with user
read -p "Update version from ${OLD_VERSION} to ${NEW_VERSION}? (y/N) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    print_info "Version update cancelled"
    exit 0
fi

################################################################################
# Update Files
################################################################################

echo ""
print_info "Updating version files..."
echo ""

# 1. Update VERSION file
print_info "1/5 Updating VERSION file..."
echo "$NEW_VERSION" > /opt/media-downloader/VERSION
print_success "VERSION file updated"

# 2. Update backend API
print_info "2/5 Updating backend API (web/backend/api.py)..."
sed -i "s/version=\"[0-9]\+\.[0-9]\+\.[0-9]\+\"/version=\"$NEW_VERSION\"/" \
    /opt/media-downloader/web/backend/api.py
print_success "Backend API version updated"

# 3. Update package.json
print_info "3/5 Updating frontend package.json..."
sed -i "s/\"version\": \"[0-9]\+\.[0-9]\+\.[0-9]\+\"/\"version\": \"$NEW_VERSION\"/" \
    /opt/media-downloader/web/frontend/package.json
print_success "package.json updated"

# 4. Update App.tsx (both locations)
print_info "4/5 Updating App.tsx (desktop and mobile menus)..."
sed -i "s/>v[0-9]\+\.[0-9]\+\.[0-9]\+</>v$NEW_VERSION</g" \
    /opt/media-downloader/web/frontend/src/App.tsx
print_success "App.tsx updated (2 locations)"

# 5. Update Configuration.tsx
print_info "5/5 Updating Configuration.tsx (About tab)..."
sed -i "s/Version [0-9]\+\.[0-9]\+\.[0-9]\+/Version $NEW_VERSION/" \
    /opt/media-downloader/web/frontend/src/pages/Configuration.tsx
sed -i "s/currently v[0-9]\+\.[0-9]\+\.[0-9]\+/currently v$NEW_VERSION/" \
    /opt/media-downloader/web/frontend/src/pages/Configuration.tsx
print_success "Configuration.tsx updated"

################################################################################
# Verification
################################################################################

echo ""
print_info "Verifying version updates..."
echo ""

# Check each file
check_file() {
    local file="$1"
    local pattern="$2"
    local description="$3"

    if grep -q "$pattern" "$file" 2>/dev/null; then
        print_success "$description"
    else
        print_error "$description - NOT FOUND!"
        return 1
    fi
}

check_file "/opt/media-downloader/VERSION" "^$NEW_VERSION$" "VERSION file"
check_file "/opt/media-downloader/web/backend/api.py" "version=\"$NEW_VERSION\"" "Backend API"
check_file "/opt/media-downloader/web/frontend/package.json" "\"version\": \"$NEW_VERSION\"" "package.json"
check_file "/opt/media-downloader/web/frontend/src/App.tsx" "v$NEW_VERSION" "App.tsx (menus)"
check_file "/opt/media-downloader/web/frontend/src/pages/Configuration.tsx" "Version $NEW_VERSION" "Configuration.tsx (About tab)"

################################################################################
# Manual Steps Reminder
################################################################################

echo ""
echo "╔════════════════════════════════════════════════╗"
echo "║           Version Update Complete              ║"
echo "╚════════════════════════════════════════════════╝"
echo ""
print_warning "MANUAL STEPS REQUIRED:"
echo ""
echo "1. Update data/changelog.json:"
echo "   - Add new version entry at the TOP of the array"
echo "   - Include version, date, title, type, and changes"
echo ""
echo "2. Update CHANGELOG.md:"
echo "   - Add new version section at the TOP (after header)"
echo "   - Document all changes, fixes, and features"
echo ""
echo "3. Restart services:"
echo "   ${BLUE}sudo systemctl restart media-downloader-api${NC}"
echo ""
echo "4. Create version backup:"
echo "   ${BLUE}bash scripts/create-version-backup.sh${NC}"
echo ""
echo "5. Verify in browser:"
echo "   - Check Health page loads correctly"
echo "   - Check Configuration → About tab shows v$NEW_VERSION"
echo "   - Check desktop/mobile menu shows v$NEW_VERSION"
echo ""
print_info "See docs/VERSION_UPDATE_CHECKLIST.md for full checklist"
echo ""
