#!/bin/bash

##############################################################################
# LatePoint Plugin Release Script
#
# This script automates the version bump process for releasing a new version
# of the LatePoint WordPress plugin.
#
# Usage: ./bin/release.sh <new_version>
# Example: ./bin/release.sh 5.2.6
##############################################################################

set -e  # Exit on error

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

# Script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PLUGIN_DIR="$(dirname "$SCRIPT_DIR")"

# File paths
MAIN_PLUGIN_FILE="$PLUGIN_DIR/latepoint.php"
README_FILE="$PLUGIN_DIR/readme.txt"
CHANGELOG_FILE="$PLUGIN_DIR/CHANGELOG.md"

##############################################################################
# Helper Functions
##############################################################################

print_header() {
    echo -e "\n${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}\n"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_info() {
    echo -e "${BLUE}ℹ $1${NC}"
}

##############################################################################
# Validation Functions
##############################################################################

validate_version_format() {
    local version=$1
    if ! [[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        print_error "Invalid version format: $version"
        print_info "Version must be in format: X.Y.Z (e.g., 5.2.6)"
        exit 1
    fi
}

validate_files_exist() {
    local missing_files=0

    if [ ! -f "$MAIN_PLUGIN_FILE" ]; then
        print_error "Main plugin file not found: $MAIN_PLUGIN_FILE"
        missing_files=1
    fi

    if [ ! -f "$README_FILE" ]; then
        print_error "README file not found: $README_FILE"
        missing_files=1
    fi

    if [ ! -f "$CHANGELOG_FILE" ]; then
        print_error "CHANGELOG file not found: $CHANGELOG_FILE"
        missing_files=1
    fi

    if [ $missing_files -eq 1 ]; then
        exit 1
    fi
}

get_current_version() {
    grep -m 1 "public \$version = " "$MAIN_PLUGIN_FILE" | sed -E "s/.*'([0-9.]+)'.*/\1/"
}

##############################################################################
# Version Bump Functions
##############################################################################

update_main_plugin_file() {
    local new_version=$1
    print_info "Updating $MAIN_PLUGIN_FILE..."

    # Update Version in plugin header comment
    sed -i.bak "s/^ \* Version: .*$/ * Version: $new_version/" "$MAIN_PLUGIN_FILE"

    # Update version property in class
    sed -i.bak "s/public \$version = '.*';/public \$version = '$new_version';/" "$MAIN_PLUGIN_FILE"

    rm -f "${MAIN_PLUGIN_FILE}.bak"
    print_success "Updated version in latepoint.php"
}

update_readme_file() {
    local new_version=$1
    print_info "Updating $README_FILE..."

    # Update Stable tag
    sed -i.bak "s/^Stable tag: .*/Stable tag: $new_version/" "$README_FILE"

    rm -f "${README_FILE}.bak"
    print_success "Updated stable tag in readme.txt"
}

update_changelog_date() {
    local new_version=$1
    local release_date=$(date "+%B %-d, %Y")

    print_info "Updating CHANGELOG.md release date..."

    # Update TBD to actual date for the current version
    sed -i.bak "s/## \[$new_version\] - TBD/## [$new_version] - $release_date/" "$CHANGELOG_FILE"

    rm -f "${CHANGELOG_FILE}.bak"
    print_success "Updated release date in CHANGELOG.md to $release_date"
}


update_readme_changelog() {
    local new_version=$1

    print_info "Extracting last 5 changelogs from CHANGELOG.md..."

    # Find the line number where changelog section starts in readme.txt
    local changelog_start=$(grep -n "^== Changelog ==" "$README_FILE" | cut -d: -f1)

    if [ -z "$changelog_start" ]; then
        print_error "Could not find '== Changelog ==' section in readme.txt"
        return 1
    fi

    # Create temporary file with updated changelog
    local temp_file=$(mktemp)

    # Copy everything before changelog section
    head -n $changelog_start "$README_FILE" > "$temp_file"

    # Add empty line after header
    echo "" >> "$temp_file"

    # Process CHANGELOG.md and extract last 5 versions
    local version_count=0
    local in_version=false
    local current_section=""
    local section_prefix=""

    while IFS= read -r line; do
        # Match version header: ## [X.Y.Z] - Date
        if [[ $line =~ ^##\ \[([0-9.]+)\]\ -\ (.+)$ ]]; then
            # Check if we've already processed 5 versions
            if [ $version_count -ge 5 ]; then
                break
            fi

            version="${BASH_REMATCH[1]}"
            date="${BASH_REMATCH[2]}"

            # Add blank line before new version (except first one)
            if [ $version_count -gt 0 ]; then
                echo "" >> "$temp_file"
            fi

            echo "= $version - $date =" >> "$temp_file"
            in_version=true
            current_section=""
            ((version_count++))
            continue
        fi

        if [ "$in_version" = true ]; then
            # Match section headers and map to prefixes
            if [[ $line =~ ^###\ (.+)$ ]]; then
                current_section="${BASH_REMATCH[1]}"

                case "$current_section" in
                    "Added")
                        section_prefix="New"
                        ;;
                    "Fixed")
                        section_prefix="Fix"
                        ;;
                    "Changed"|"Improved")
                        section_prefix="Improvement"
                        ;;
                    "Security")
                        section_prefix="Security"
                        ;;
                    "Deprecated")
                        section_prefix="Deprecated"
                        ;;
                    "Removed")
                        section_prefix="Removed"
                        ;;
                    *)
                        section_prefix=""
                        ;;
                esac
                continue
            fi

            # Match bullet points and add prefix
            if [[ $line =~ ^-\ (.+)$ ]]; then
                content="${BASH_REMATCH[1]}"
                if [ -n "$section_prefix" ]; then
                    echo "- $section_prefix: $content" >> "$temp_file"
                else
                    echo "- $content" >> "$temp_file"
                fi
            fi
        fi
    done < "$CHANGELOG_FILE"

    # Add blank line and link to full changelog
    echo "" >> "$temp_file"
    echo "Full changelog can be found on our website: [Full Changelog](https://latepoint.com/changelog/)" >> "$temp_file"

    # Replace readme.txt with updated version
    mv "$temp_file" "$README_FILE"

    print_success "Updated last 5 changelogs in readme.txt"
}

##############################################################################
# Git Functions
##############################################################################

check_git_status() {
    local skip_prompt=$1

    print_info "Checking git status..."

    if ! git -C "$PLUGIN_DIR" rev-parse --git-dir > /dev/null 2>&1; then
        print_warning "Not a git repository. Skipping git checks."
        return 1
    fi

    if [ -n "$(git -C "$PLUGIN_DIR" status --porcelain)" ]; then
        print_warning "Working directory has uncommitted changes."

        if [ "$skip_prompt" = true ]; then
            print_info "Auto-continuing due to --yes flag"
        else
            echo -n "Continue anyway? (y/n) "
            read -r response
            if [[ ! $response =~ ^[Yy]$ ]]; then
                exit 1
            fi
        fi
    fi

    return 0
}

##############################################################################
# Main Release Process
##############################################################################

main() {
    print_header "LatePoint Release Script"

    local new_version=""
    local skip_confirmations=false

    # Parse command line arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            --help|-h)
                echo "Usage: $0 [OPTIONS] [version]"
                echo ""
                echo "LatePoint WordPress Plugin Release Script"
                echo "Automates version bumping and changelog management"
                echo ""
                echo "Options:"
                echo "  --ver=VERSION, --version=VERSION    Specify version number"
                echo "  --yes, -y                           Skip all confirmations"
                echo "  --help, -h                          Show this help message"
                echo ""
                echo "Examples:"
                echo "  $0                          # Interactive mode (prompts for version)"
                echo "  $0 5.2.6                    # Bump to version 5.2.6 with confirmations"
                echo "  $0 --ver=5.2.6 --yes        # Bump to 5.2.6 without confirmations"
                echo "  $0 --version 5.2.6 -y       # Same as above (short syntax)"
                echo ""
                echo "What this script does:"
                echo "  1. Updates version in latepoint.php (header and class property)"
                echo "  2. Updates stable tag in readme.txt"
                echo "  3. Updates release date in CHANGELOG.md (TBD -> current date)"
                echo "  4. Extracts last 5 changelogs from CHANGELOG.md to readme.txt"
                echo "  5. Converts changelog format (Keep a Changelog -> WordPress)"
                exit 0
                ;;
            --ver=*)
                new_version="${1#*=}"
                shift
                ;;
            --version=*)
                new_version="${1#*=}"
                shift
                ;;
            --ver|--version)
                new_version="$2"
                shift 2
                ;;
            --yes|-y)
                skip_confirmations=true
                shift
                ;;
            -*)
                print_error "Unknown option: $1"
                echo "Usage: $0 [OPTIONS] [version]"
                echo ""
                echo "Options:"
                echo "  --ver=VERSION, --version=VERSION    Specify version number"
                echo "  --yes, -y                           Skip all confirmations"
                echo "  --help, -h                          Show help message"
                echo ""
                echo "Examples:"
                echo "  $0 5.2.6"
                echo "  $0 --ver=5.2.6 --yes"
                echo "  $0 --version 5.2.6 -y"
                echo ""
                echo "Run '$0 --help' for more information"
                exit 1
                ;;
            *)
                # Positional argument (version number)
                if [ -z "$new_version" ]; then
                    new_version="$1"
                fi
                shift
                ;;
        esac
    done

    # If version not provided, prompt for it
    if [ -z "$new_version" ]; then
        echo -n "Enter new version number (e.g., 5.2.6): "
        read -r new_version

        # Check if user entered something
        if [ -z "$new_version" ]; then
            print_error "No version specified"
            echo "Usage: $0 [OPTIONS] [version]"
            echo "Example: $0 5.2.6"
            exit 1
        fi
    fi

    # Validate version format
    validate_version_format "$new_version"

    # Validate required files exist
    validate_files_exist

    # Get current version
    local current_version=$(get_current_version)

    print_info "Current version: $current_version"
    print_info "New version: $new_version"

    # Check git status (if it's a git repo)
    check_git_status "$skip_confirmations"

    # Confirm before proceeding
    if [ "$skip_confirmations" = true ]; then
        print_info "Auto-proceeding due to --yes flag"
    else
        echo ""
        echo -n "Proceed with version bump? (y/n) "
        read -r response
        if [[ ! $response =~ ^[Yy]$ ]]; then
            print_warning "Release cancelled"
            exit 0
        fi
    fi

    print_header "Updating Version Numbers"

    # 1. Update main plugin file
    update_main_plugin_file "$new_version"

    # 2. Update readme.txt
    update_readme_file "$new_version"

    # 3. Update CHANGELOG.md date
    update_changelog_date "$new_version"

    print_header "Updating Changelog in readme.txt"

    # 4. Copy last 5 changelogs to readme.txt
    update_readme_changelog "$new_version"

    print_header "Release Steps Completed"

    print_success "Version bumped from $current_version to $new_version"
    print_info "Files updated:"
    echo "  - latepoint.php"
    echo "  - readme.txt"
    echo "  - CHANGELOG.md"
}

# Run main function
main "$@"
