#!/bin/bash
#
# Django App Versioning & Release Script
# Replaces: git add . && git commit -m "..." && git push
# Usage: ./commit
#

set -e

# ==================== CONFIG & SETUP ====================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/release.config.sh"

# Strip carriage returns from all variables (fixes Windows line ending issues)
SSH_USER=$(echo "$SSH_USER" | tr -d '\r')
SSH_HOST=$(echo "$SSH_HOST" | tr -d '\r')
SSH_PORT=$(echo "$SSH_PORT" | tr -d '\r')
REMOTE_RELEASE_DIR=$(echo "$REMOTE_RELEASE_DIR" | tr -d '\r')
REMOTE_FILES_DIR=$(echo "$REMOTE_FILES_DIR" | tr -d '\r')
REMOTE_HTML_DIR=$(echo "$REMOTE_HTML_DIR" | tr -d '\r')
APP_NAME=$(echo "$APP_NAME" | tr -d '\r')

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

# ==================== LOGGING FUNCTIONS ====================
log_info() { echo -e "${BLUE}ℹ ${1}${NC}" >&2; }
log_success() { echo -e "${GREEN}✓ ${1}${NC}" >&2; }
log_warning() { echo -e "${YELLOW}⚠ ${1}${NC}" >&2; }
log_error() { echo -e "${RED}✗ ${1}${NC}" >&2; }

# ==================== HELPER FUNCTIONS ====================

# Read current version from VERSION file
read_version() {
    if [ ! -f "$VERSION_FILE" ]; then
        echo "1.0.0" > "$VERSION_FILE"
        log_warning "VERSION file not found. Created with version 1.0.0"
    fi
    cat "$VERSION_FILE" | tr -d '\n'
}

# Parse semantic version
parse_version() {
    local version=$1
    IFS='.' read -r MAJOR MINOR PATCH <<< "$version"
    echo "$MAJOR $MINOR $PATCH"
}

# Calculate new version based on choice
calculate_version() {
    local current_version=$1
    local choice=$2
    
    read -r MAJOR MINOR PATCH <<< "$(parse_version "$current_version")"
    
    case $choice in
        1) echo "$MAJOR.$MINOR.$((PATCH + 1)) patch" ;;
        2) echo "$MAJOR.$((MINOR + 1)).0 minor" ;;
        3) echo "$((MAJOR + 1)).0.0 major" ;;
        4) echo "$current_version dev" ;;
        *) log_error "Invalid option"; return 1 ;;
    esac
}

# Prompt for commit message
prompt_commit_message() {
    echo "" >&2
    echo -e "${BLUE}=== Commit Message ===${NC}" >&2
    echo "Enter the commit message:" >&2
    read -r COMMIT_MSG

    if [ -z "$COMMIT_MSG" ]; then
        log_error "Commit message cannot be empty"
        return 1
    fi

    echo "$COMMIT_MSG"
}
# Read release notes from user
read_release_notes() {
    local notes=""
    while true; do
        read -r line
        if [ "$line" = "END" ]; then
            break
        fi
        notes="${notes}${line}"$'\n'
    done
    
    # Remove trailing newline and output
    echo "${notes%$'\n'}"
}

# Update VERSION file
update_version_file() {
    local new_version=$1
    echo "$new_version" > "$VERSION_FILE"
    log_success "VERSION file updated to $new_version"
}

# Update release notes markdown (clean, no ANSI codes)
update_release_notes() {
    local version=$1
    local commit_msg=$2
    local release_notes=$3
    local date=$(date +%Y-%m-%d)
    
    # Strip ANSI color codes from release notes
    local clean_notes=$(echo "$release_notes" | sed 's/\x1b\[[0-9;]*m//g')
    
    local header="## Version $version - $date"
    local entry="${header}"$'\n'"**Commit:** ${commit_msg}"$'\n'"${clean_notes}"
    
    if [ -f "$RELEASE_NOTES_FILE" ]; then
        # Check if file has a main title
        if head -1 "$RELEASE_NOTES_FILE" | grep -q "^# "; then
            # Insert after title
            {
                head -1 "$RELEASE_NOTES_FILE"
                echo ""
                echo "$entry"
                echo ""
                tail -n +2 "$RELEASE_NOTES_FILE"
            } > /tmp/release_notes_new.md
            mv /tmp/release_notes_new.md "$RELEASE_NOTES_FILE"
        else
            # Prepend to file
            {
                echo "$entry"
                echo ""
                cat "$RELEASE_NOTES_FILE"
            } > /tmp/release_notes_new.md
            mv /tmp/release_notes_new.md "$RELEASE_NOTES_FILE"
        fi
    else
        # Create new file
        {
            echo "# Release Notes"
            echo ""
            echo "$entry"
        } > "$RELEASE_NOTES_FILE"
    fi
    
    log_success "RELEASE_NOTES.md updated"
}

# Git operations
git_operations() {
    local commit_msg=$1
    
    log_info "Running: git add ."
    git add .
    log_success "Changes staged"
    
    log_info "Running: git commit -m '$commit_msg'"
    git commit -m "$commit_msg"
    log_success "Commit created"
    
    log_info "Running: git push"
    git push
    log_success "Pushed to repository"
}

# Create zip archive respecting .gitignore
create_release_zip() {
    local version=$1
    
    mkdir -p "$ARTIFACTS_DIR"
    
    local zip_filename="${APP_NAME}-${version}.zip"
    local zip_path="${ARTIFACTS_DIR}/${zip_filename}"
    
    log_info "Creating zip archive: $zip_filename"
    log_info "(Only git-tracked files included, respecting .gitignore)"
    
    cd "$PROJECT_ROOT"
    git archive --format zip --output "$zip_path" HEAD
    
    if [ ! -f "$zip_path" ]; then
        log_error "Failed to create zip file"
        exit 1
    fi
    
    local zip_size=$(du -h "$zip_path" | cut -f1)
    log_success "Zip created: $zip_filename ($zip_size)"
    echo "$zip_path"
}

# Upload to remote server via SCP
upload_to_server() {
    local version=$1
    local zip_path=$2
    local zip_filename=$3
    
    log_info "Connecting to server: ${SSH_USER}@${SSH_HOST}:${SSH_PORT}"
    
    # Ensure remote directories exist
    log_info "Creating remote directories..."
    if ssh -p "$SSH_PORT" "${SSH_USER}@${SSH_HOST}" "mkdir -p '${REMOTE_FILES_DIR}' && mkdir -p '${REMOTE_HTML_DIR}'"; then
        log_success "Remote directories ready"
    else
        log_error "Failed to create remote directories"
        exit 1
    fi
    
    # Upload zip
    log_info "Uploading application zip..."
    log_info "Running: scp -P $SSH_PORT '$zip_path' '${SSH_USER}@${SSH_HOST}:${REMOTE_FILES_DIR}/${zip_filename}'"
    
    scp -P "$SSH_PORT" "$zip_path" "${SSH_USER}@${SSH_HOST}:${REMOTE_FILES_DIR}/${zip_filename}" 2>&1 || {
        log_error "Failed to upload zip"
        exit 1
    }
    log_success "Zip uploaded"
    
    # Upload release notes
    log_info "Uploading release notes..."
    if scp -P "$SSH_PORT" "$RELEASE_NOTES_FILE" "${SSH_USER}@${SSH_HOST}:${REMOTE_HTML_DIR}/RELEASE_NOTES.md"; then
        log_success "Release notes uploaded"
    else
        log_error "Failed to upload release notes"
        exit 1
    fi
}

# Generate static HTML release page
generate_release_html() {
    local version="$1"
    local zip_filename="$2"
    local html_path="${ARTIFACTS_DIR}/index.html"

    log_info "Generating release page..."

    # -------------------------------------------------------------------------
    # Validate RELEASE_NOTES.md
    # -------------------------------------------------------------------------
    if [ ! -f "$RELEASE_NOTES_FILE" ]; then
        log_error "Release notes file not found: $RELEASE_NOTES_FILE"
        return 1
    fi

    mkdir -p "$ARTIFACTS_DIR"

    # -------------------------------------------------------------------------
    # Read application name safely
    # -------------------------------------------------------------------------
    local display_name="$APP_NAME"

    # Escape HTML-sensitive characters
    html_escape() {
        printf '%s' "$1" \
            | sed \
                -e 's/&/\&amp;/g' \
                -e 's/</\&lt;/g' \
                -e 's/>/\&gt;/g' \
                -e 's/"/\&quot;/g' \
                -e "s/'/&#39;/g"
    }

    local escaped_app_name
    escaped_app_name=$(html_escape "$display_name")

    # -------------------------------------------------------------------------
    # Build release cards from RELEASE_NOTES.md
    #
    # Expected format:
    #
    # # Release Notes
    #
    # ## Version 1.0.8 - 2026-10-03
    # **Commit:** Added stock filtering
    #
    # - Added ...
    # - Fixed ...
    #
    # ## Version 1.0.7 - 2026-09-28
    # **Commit:** ...
    #
    # - ...
    # -------------------------------------------------------------------------

    local releases_html=""
    local release_count=0

    # Temporary files used while parsing
    local current_version=""
    local current_date=""
    local current_commit=""
    local current_notes=""

    # -------------------------------------------------------------------------
    # Helper: convert simple Markdown in release notes to HTML
    # -------------------------------------------------------------------------
    markdown_to_html() {
        local text="$1"

        printf '%s\n' "$text" | while IFS= read -r line; do

            # Escape HTML first
            line=$(html_escape "$line")

            # Empty line
            if [ -z "$line" ]; then
                echo "<div class=\"note-spacer\"></div>"
                continue
            fi

            # Markdown bullet
            if [[ "$line" =~ ^[[:space:]]*-[[:space:]]+(.*)$ ]]; then
                echo "<li>${BASH_REMATCH[1]}</li>"
                continue
            fi

            # Markdown numbered list
            if [[ "$line" =~ ^[[:space:]]*[0-9]+\.[[:space:]]+(.*)$ ]]; then
                echo "<li>${BASH_REMATCH[1]}</li>"
                continue
            fi

            # Markdown headings
            if [[ "$line" =~ ^###[[:space:]]+(.*)$ ]]; then
                echo "<h5>${BASH_REMATCH[1]}</h5>"
                continue
            fi

            if [[ "$line" =~ ^##[[:space:]]+(.*)$ ]]; then
                echo "<h4>${BASH_REMATCH[1]}</h4>"
                continue
            fi

            # Bold text: **text**
            line=$(echo "$line" | sed -E 's/\*\*([^*]+)\*\*/<strong>\1<\/strong>/g')

            # Inline code: `code`
            line=$(echo "$line" | sed -E 's/`([^`]+)`/<code>\1<\/code>/g')

            echo "<p>${line}</p>"

        done
    }

    # -------------------------------------------------------------------------
    # Helper: generate one release card
    # -------------------------------------------------------------------------
    generate_release_card() {
        local rel_version="$1"
        local rel_date="$2"
        local rel_commit="$3"
        local rel_notes="$4"
        local is_latest="$5"

        local escaped_version
        local escaped_date
        local escaped_commit
        local zip_name
        local escaped_zip

        escaped_version=$(html_escape "$rel_version")
        escaped_date=$(html_escape "$rel_date")
        escaped_commit=$(html_escape "$rel_commit")

        zip_name="${APP_NAME}-${rel_version}.zip"
        escaped_zip=$(html_escape "$zip_name")

        local latest_badge=""
        local card_class="release-card"

        if [ "$is_latest" = "true" ]; then
            latest_badge='<span class="latest-badge">LATEST</span>'
            card_class="release-card latest-release"
        fi

        local notes_html=""
        if [ -n "$rel_notes" ]; then
            notes_html=$(markdown_to_html "$rel_notes")
        else
            notes_html="<p class=\"no-notes\">No release notes provided.</p>"
        fi

        cat <<EOF
        <article class="${card_class}">
            <div class="release-header">
                <div>
                    <div class="version-row">
                        <h2>v${escaped_version}</h2>
                        ${latest_badge}
                    </div>

                    <div class="release-date">
                        Released ${escaped_date}
                    </div>
                </div>

                <a
                    class="download-button"
                    href="/files/${escaped_zip}"
                    download
                >
                    <span class="download-icon">↓</span>
                    Download
                </a>
            </div>

            <div class="release-body">

                <div class="commit-section">
                    <div class="section-label">
                        COMMIT
                    </div>

                    <div class="commit-message">
                        ${escaped_commit}
                    </div>
                </div>

                <div class="changes-section">
                    <div class="section-label">
                        WHAT'S NEW
                    </div>

                    <div class="release-notes">
                        ${notes_html}
                    </div>
                </div>

            </div>

            <div class="release-footer">
                <span>${escaped_zip}</span>

                <a href="/files/${escaped_zip}">
                    Download release
                </a>
            </div>
        </article>
EOF
    }

    # -------------------------------------------------------------------------
    # Parse RELEASE_NOTES.md
    # -------------------------------------------------------------------------

    while IFS= read -r line || [ -n "$line" ]; do

        # -------------------------------------------------------------
        # New version detected
        # -------------------------------------------------------------
        if [[ "$line" =~ ^##[[:space:]]+Version[[:space:]]+([^[:space:]]+)[[:space:]]+-[[:space:]]+(.+)$ ]]; then

            # If we already have a release, generate its card first
            if [ -n "$current_version" ]; then

                release_count=$((release_count + 1))

                local is_latest="false"

                if [ "$release_count" -eq 1 ]; then
                    is_latest="true"
                fi

                releases_html+=$(generate_release_card \
                    "$current_version" \
                    "$current_date" \
                    "$current_commit" \
                    "$current_notes" \
                    "$is_latest")
            fi

            # Start new release
            current_version="${BASH_REMATCH[1]}"
            current_date="${BASH_REMATCH[2]}"
            current_commit=""
            current_notes=""

            continue
        fi

        # -------------------------------------------------------------
        # Commit line
        # -------------------------------------------------------------
        if [[ "$line" =~ ^\*\*Commit:\*\*[[:space:]]*(.*)$ ]]; then
            current_commit="${BASH_REMATCH[1]}"
            continue
        fi

        # -------------------------------------------------------------
        # Ignore main title
        # -------------------------------------------------------------
        if [[ "$line" == "# Release Notes" ]]; then
            continue
        fi

        # -------------------------------------------------------------
        # Add everything else to release notes
        # -------------------------------------------------------------
        if [ -n "$current_version" ]; then

            if [ -z "$current_notes" ]; then
                current_notes="$line"
            else
                current_notes="${current_notes}"$'\n'"${line}"
            fi

        fi

    done < "$RELEASE_NOTES_FILE"

    # -------------------------------------------------------------------------
    # Add the final release
    # -------------------------------------------------------------------------
    if [ -n "$current_version" ]; then

        release_count=$((release_count + 1))

        local is_latest="false"

        if [ "$release_count" -eq 1 ]; then
            is_latest="true"
        fi

        releases_html+=$(generate_release_card \
            "$current_version" \
            "$current_date" \
            "$current_commit" \
            "$current_notes" \
            "$is_latest")
    fi

    # -------------------------------------------------------------------------
    # No releases found
    # -------------------------------------------------------------------------
    if [ "$release_count" -eq 0 ]; then
        log_error "No releases found in $RELEASE_NOTES_FILE"
        return 1
    fi

    # -------------------------------------------------------------------------
    # Generate complete HTML page
    # -------------------------------------------------------------------------
    cat > "$html_path" <<EOF
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">

    <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0"
    >

    <meta
        name="description"
        content="${escaped_app_name} release history and downloads"
    >

    <title>${escaped_app_name} - Releases</title>

    <style>

        * {
            box-sizing: border-box;
        }

        html {
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            padding: 0;

            font-family:
                -apple-system,
                BlinkMacSystemFont,
                "Segoe UI",
                Roboto,
                Helvetica,
                Arial,
                sans-serif;

            background: #f5f7fb;
            color: #1f2937;
            line-height: 1.6;
        }

        /* ------------------------------------------------------------
           Header
        ------------------------------------------------------------ */

        .hero {
            background: linear-gradient(
                135deg,
                #111827 0%,
                #1f2937 100%
            );

            color: white;

            padding: 55px 20px;
        }

        .hero-container {
            max-width: 1000px;
            margin: 0 auto;
        }

        .hero h1 {
            margin: 0 0 10px;

            font-size: 38px;
            font-weight: 700;

            letter-spacing: -0.8px;
        }

        .hero p {
            margin: 0;

            color: #cbd5e1;

            font-size: 17px;
        }

        .release-count {
            display: inline-block;

            margin-top: 20px;

            padding: 6px 13px;

            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 20px;

            background: rgba(255,255,255,0.08);

            font-size: 13px;
            color: #e5e7eb;
        }

        /* ------------------------------------------------------------
           Main
        ------------------------------------------------------------ */

        .container {
            max-width: 1000px;

            margin: 0 auto;

            padding: 45px 20px 70px;
        }

        .section-title {
            margin: 0 0 25px;

            font-size: 24px;
            font-weight: 700;

            color: #111827;
        }

        /* ------------------------------------------------------------
           Release card
        ------------------------------------------------------------ */

        .release-card {
            position: relative;

            margin-bottom: 28px;

            background: white;

            border: 1px solid #e5e7eb;

            border-radius: 14px;

            overflow: hidden;

            box-shadow:
                0 4px 14px rgba(15, 23, 42, 0.05);
        }

        .latest-release {
            border: 2px solid #2563eb;

            box-shadow:
                0 8px 25px rgba(37, 99, 235, 0.12);
        }

        .release-header {
            display: flex;

            align-items: center;
            justify-content: space-between;

            gap: 20px;

            padding: 25px 28px;

            border-bottom: 1px solid #eef0f4;
        }

        .version-row {
            display: flex;

            align-items: center;

            gap: 12px;
        }

        .version-row h2 {
            margin: 0;

            font-size: 25px;
            font-weight: 700;

            color: #111827;
        }

        .latest-badge {
            display: inline-block;

            padding: 4px 9px;

            border-radius: 5px;

            background: #2563eb;
            color: white;

            font-size: 10px;
            font-weight: 700;

            letter-spacing: 0.7px;
        }

        .release-date {
            margin-top: 4px;

            color: #6b7280;

            font-size: 14px;
        }

        /* ------------------------------------------------------------
           Download button
        ------------------------------------------------------------ */

        .download-button {
            display: inline-flex;

            align-items: center;
            justify-content: center;

            gap: 8px;

            padding: 11px 18px;

            border-radius: 8px;

            background: #2563eb;
            color: white;

            text-decoration: none;

            font-size: 14px;
            font-weight: 600;

            white-space: nowrap;

            transition:
                background 0.2s ease,
                transform 0.2s ease;
        }

        .download-button:hover {
            background: #1d4ed8;

            transform: translateY(-1px);
        }

        .download-icon {
            font-size: 18px;

            line-height: 1;
        }

        /* ------------------------------------------------------------
           Release body
        ------------------------------------------------------------ */

        .release-body {
            padding: 25px 28px;
        }

        .commit-section {
            margin-bottom: 25px;
        }

        .section-label {
            margin-bottom: 8px;

            color: #6b7280;

            font-size: 11px;
            font-weight: 700;

            letter-spacing: 1px;
            text-transform: uppercase;
        }

        .commit-message {
            padding: 12px 14px;

            background: #f8fafc;

            border-left: 3px solid #94a3b8;

            border-radius: 5px;

            color: #374151;

            font-size: 14px;
        }

        .release-notes {
            color: #374151;

            font-size: 15px;
        }

        .release-notes p {
            margin: 0 0 10px;
        }

        .release-notes p:last-child {
            margin-bottom: 0;
        }

        .release-notes ul {
            margin: 8px 0 15px;

            padding-left: 23px;
        }

        .release-notes li {
            margin-bottom: 6px;
        }

        .release-notes strong {
            color: #111827;
        }

        .release-notes code {
            padding: 2px 6px;

            background: #f1f5f9;

            border-radius: 4px;

            font-family:
                "SFMono-Regular",
                Consolas,
                "Liberation Mono",
                monospace;

            font-size: 13px;
        }

        .release-notes h4,
        .release-notes h5 {
            margin-top: 18px;
            margin-bottom: 8px;

            color: #111827;
        }

        .note-spacer {
            height: 5px;
        }

        .no-notes {
            color: #9ca3af;
            font-style: italic;
        }

        /* ------------------------------------------------------------
           Footer inside release card
        ------------------------------------------------------------ */

        .release-footer {
            display: flex;

            align-items: center;
            justify-content: space-between;

            gap: 15px;

            padding: 13px 28px;

            background: #fafafa;

            border-top: 1px solid #eef0f4;

            color: #6b7280;

            font-size: 12px;
        }

        .release-footer span {
            overflow: hidden;

            text-overflow: ellipsis;

            white-space: nowrap;

            font-family:
                "SFMono-Regular",
                Consolas,
                "Liberation Mono",
                monospace;
        }

        .release-footer a {
            color: #2563eb;

            text-decoration: none;

            font-weight: 600;

            white-space: nowrap;
        }

        .release-footer a:hover {
            text-decoration: underline;
        }

        /* ------------------------------------------------------------
           Page footer
        ------------------------------------------------------------ */

        .page-footer {
            padding: 25px 20px 45px;

            text-align: center;

            color: #6b7280;

            font-size: 13px;
        }

        .page-footer a {
            color: #2563eb;

            text-decoration: none;
        }

        /* ------------------------------------------------------------
           Mobile
        ------------------------------------------------------------ */

        @media (max-width: 650px) {

            .hero {
                padding: 40px 20px;
            }

            .hero h1 {
                font-size: 30px;
            }

            .container {
                padding: 30px 15px 50px;
            }

            .release-header {
                align-items: flex-start;

                flex-direction: column;

                padding: 20px;
            }

            .download-button {
                width: 100%;
            }

            .release-body {
                padding: 20px;
            }

            .release-footer {
                align-items: flex-start;

                flex-direction: column;

                padding: 13px 20px;
            }

            .release-footer span {
                width: 100%;
            }

        }

    </style>

</head>

<body>

    <header class="hero">

        <div class="hero-container">

            <h1>${escaped_app_name}</h1>

            <p>
                Release history, changes and downloadable versions
            </p>

            <div class="release-count">
                ${release_count} release$( [ "$release_count" -eq 1 ] && echo "" || echo "s" )
            </div>

        </div>

    </header>


    <main class="container">

        <h2 class="section-title">
            Releases
        </h2>

        ${releases_html}

    </main>


    <footer class="page-footer">

        <div>
            ${escaped_app_name} Release Management
        </div>

        <div>
            Generated automatically during deployment
        </div>

    </footer>

</body>
</html>
EOF

    # -------------------------------------------------------------------------
    # Verify generated file
    # -------------------------------------------------------------------------
    if [ ! -s "$html_path" ]; then
        log_error "Failed to generate release page"
        return 1
    fi

    log_success "Release page generated with ${release_count} release(s)"

    echo "$html_path"
}

# Upload HTML file to server
upload_html_to_server() {
    local html_path=$1
    
    log_info "Uploading release page..."
    if scp -P "$SSH_PORT" "$html_path" "${SSH_USER}@${SSH_HOST}:${REMOTE_HTML_DIR}/index.html"; then
        log_success "Release page uploaded"
    else
        log_error "Failed to upload release page"
        exit 1
    fi
}

# Cleanup local artifacts
cleanup_artifacts() {
    log_info "Cleaning up local artifacts..."
    rm -rf "$ARTIFACTS_DIR"
    log_success "Artifacts cleaned up"
}

# ==================== MAIN WORKFLOW ====================

main() {
    echo -e "${BLUE}"
    echo "╔════════════════════════════════════════╗"
    echo "║  Django App Release & Commit Tool      ║"
    echo "╚════════════════════════════════════════╝"
    echo -e "${NC}"
    
    # Validate git repo
    if ! git rev-parse --git-dir > /dev/null 2>&1; then
        log_error "Not a git repository"
        exit 1
    fi
    
    # Check for uncommitted changes
    if ! git status --porcelain | grep -q .; then
        log_warning "No changes detected"
        read -p "Continue anyway? (y/n): " -n 1 choice
        echo
        [ "$choice" != "y" ] && { log_info "Aborted"; exit 0; }
    fi
    
    cd "$PROJECT_ROOT"
    
    # === PHASE 1: VERSION & RELEASE NOTES ===
    echo -e "\n${BLUE}╔════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║  Phase 1: Version & Release Notes      ║${NC}"
    echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"
    
    CURRENT_VERSION=$(read_version)
    log_info "Current version: $CURRENT_VERSION"
    
    # === Version Bump Menu ===
    read -r MAJOR MINOR PATCH <<< "$(parse_version "$CURRENT_VERSION")"
    
    echo -e "\n${BLUE}=== Version Bump ===${NC}"
    echo "Current version: $CURRENT_VERSION"
    echo ""
    echo "1) Patch (bug fixes:      $MAJOR.$MINOR.$((PATCH + 1)))"
    echo "2) Minor (new features:   $MAJOR.$((MINOR + 1)).0)"
    echo "3) Major (breaking:       $((MAJOR + 1)).0.0)"
    echo "4) Skip versioning (dev)"
    echo ""
    read -p "Select option [1-4]: " -n 1 version_choice
    echo
    
    read -r NEW_VERSION VERSION_TYPE <<< "$(calculate_version "$CURRENT_VERSION" "$version_choice")" || exit 1
    
    COMMIT_MSG=$(prompt_commit_message)
    
    RELEASE_NOTES=""
    if [ "$VERSION_TYPE" != "dev" ]; then
        # Display release notes prompt
        echo -e "\n${BLUE}=== Release Notes ===${NC}"
        echo "Enter release notes (features/bug fixes/improvements)."
        echo "Type 'END' on a new line when finished:"
        echo ""
        
        # Read release notes
        RELEASE_NOTES=$(read_release_notes)
        
        update_version_file "$NEW_VERSION"
        update_release_notes "$NEW_VERSION" "$COMMIT_MSG" "$RELEASE_NOTES"
    fi
    
    log_success "Phase 1 completed"
    
    # === PHASE 2: GIT OPERATIONS ===
    echo -e "\n${BLUE}╔════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║  Phase 2: Git Operations              ║${NC}"
    echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"
    git_operations "$COMMIT_MSG"
    log_success "Phase 2 completed"
    
    # === PHASE 3: RELEASE (if not dev) ===
    if [ "$VERSION_TYPE" != "dev" ]; then
        echo -e "\n${BLUE}╔════════════════════════════════════════╗${NC}"
        echo -e "${BLUE}║  Phase 3: Creating Release Package    ║${NC}"
        echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"
        
        ZIP_PATH=$(create_release_zip "$NEW_VERSION")
        ZIP_FILENAME=$(basename "$ZIP_PATH")
        
        upload_to_server "$NEW_VERSION" "$ZIP_PATH" "$ZIP_FILENAME"
        
        HTML_PATH=$(generate_release_html "$NEW_VERSION" "$ZIP_FILENAME")
        upload_html_to_server "$HTML_PATH"
        
        cleanup_artifacts
        
        log_success "Phase 3 completed"
    else
        log_info "Development commit (no release package created)"
    fi
    
    echo
    echo -e "${GREEN}╔════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║  ✨ All operations completed!          ║${NC}"
    echo -e "${GREEN}╚════════════════════════════════════════╝${NC}"
    echo -e "\n${BLUE}Release page: https://your-release-domain.com/html/${NC}\n"
}

main
