#!/bin/bash
#
# do the necessary things to build and publish python project
#

# Status tracking: 0=pending, 1=done, 2=failed, 3=unavailable (N/A)
declare -a STATUS=(0 0 0 0 0 0 0)

# Check prerequisites and mark unavailable steps
check_prerequisites() {
    # Check if README.org exists for step 1
    if [ ! -f README.org ]; then
        STATUS[0]=3
    fi
    # Check if .bumpversion.cfg exists for step 4
    if [ ! -f .bumpversion.cfg ]; then
        STATUS[3]=3
    fi
}

# Run prerequisite check at startup
check_prerequisites

# Action functions
action_1_convert_readme() {
    if [ -f README.org ]; then
        echo "📝 Converting README.org to README.md..."
        if pandoc README.org -o README.md; then
            STATUS[0]=1
            echo "✅ README.org converted to README.md"
        else
            STATUS[0]=2
            echo "❌ Failed to convert README.org"
        fi
    else
        echo "⚠️  README.org not found - step not applicable"
        STATUS[0]=3
    fi
}

action_2_git_check() {
    git diff --quiet && git diff --cached --quiet && [ -z "$(git ls-files --others --exclude-standard)" ]

    if [ "$?" != "0" ]; then
        echo "x... git is not clean... committing automatically"
        sleep 1
        if git commit -a -m "debug with automatic commit"; then
            STATUS[1]=1
            echo "✓ Git auto-commit successful"
        else
            STATUS[1]=2
            echo "✗ Git auto-commit failed"
        fi
    else
        echo "i... git is clean"
        STATUS[1]=1
    fi
}

action_3_clean_dist() {
    if [ -d "dist" ]; then
        echo "i... cleaning dist/"
        if rm -f dist/*; then
            STATUS[2]=1
            echo "✓ dist/ cleaned"
        else
            STATUS[2]=2
            echo "✗ Failed to clean dist/"
        fi
    else
        echo "✗ dist/ doesn't exist, cannot clean"
        STATUS[2]=2
    fi
}

action_4_bump_version() {
    if [ ! -f .bumpversion.cfg ]; then
        echo "⚠️  .bumpversion.cfg not found - step not applicable"
        STATUS[3]=3
        return
    fi

    echo "🔖 Bumping version (patch)..."
    if bumpversion patch; then
        echo "📤 Pushing to origin with tags..."
        if git push origin --all && git push origin --tags; then
            STATUS[3]=1
            echo "✅ Version bumped and pushed"
        else
            STATUS[3]=2
            echo "❌ Failed to push to origin"
        fi
    else
        STATUS[3]=2
        echo "❌ Failed to bump version"
    fi
}

action_5_build() {
    echo "i... running uv build"
    if uv build; then
        STATUS[4]=1
        echo "✓ Build successful"
    else
        STATUS[4]=2
        echo "✗ Build failed"
    fi
}

action_6_publish() {
    echo "i... publishing to PyPI"
    tok=$(cat ~/.pypirc | grep pass | awk '{print$3}')
    if [ -z "$tok" ]; then
        STATUS[5]=2
        echo "✗ Failed to read token from ~/.pypirc"
        return
    fi

    if uv publish --username __token__ --password "$tok"; then
        STATUS[5]=1
        echo "✓ Published to PyPI"
    else
        STATUS[5]=2
        echo "✗ Failed to publish to PyPI"
    fi
}

action_7_install() {
    echo "i... installing package with uv tool"
    if uv tool install jusfltuls --upgrade; then
        STATUS[6]=1
        echo "✓ Package installed/upgraded"
    else
        STATUS[6]=2
        echo "✗ Failed to install package"
    fi
}

# Display menu
show_menu() {
    clear
    # symbols: 0=pending, 1=done, 2=failed, 3=unavailable
    local symbols=("☐" "☑" "☒" "⊘")
    local colors=("\033[90m" "\033[32m" "\033[31m" "\033[33m")
    local reset="\033[0m"

    # Count completed, failed, and unavailable
    local completed=0
    local failed=0
    local unavailable=0
    for s in "${STATUS[@]}"; do
        [ "$s" -eq 1 ] && ((completed++))
        [ "$s" -eq 2 ] && ((failed++))
        [ "$s" -eq 3 ] && ((unavailable++))
    done

    # Progress bar (only count non-unavailable items)
    local total=${#STATUS[@]}
    local applicable=$((total - unavailable))
    local progress=0
    if [ $applicable -gt 0 ]; then
        progress=$((completed * 100 / applicable))
    fi
    local filled=$((progress * 30 / 100))
    local empty=$((30 - filled))
    local bar=""
    for ((i=0; i<filled; i++)); do bar="${bar}█"; done
    for ((i=0; i<empty; i++)); do bar="${bar}░"; done

    # Use printf consistently for all output to avoid alignment issues
    printf "╔════════════════════════════════════════════════════════════════╗\n"
    printf "║     📦 DISTCHECK - Python Package Publishing Workflow          ║\n"
    printf "╚════════════════════════════════════════════════════════════════╝\n"
    printf "\n"
    printf "┌────────────────────────────────────────────────────────────────┐\n"
    printf "│  WORKFLOW STEPS:                                               │\n"
    printf "├────┬──────────┬────────────────────────────────────────────────┤\n"
    printf "│ %s │ ${colors[${STATUS[0]}]}%-8s${reset}   │ %-46s   │\n" " 1" "${symbols[${STATUS[0]}]}" "Convert README.org → README.md"
    printf "│ %s │ ${colors[${STATUS[1]}]}%-8s${reset}   │ %-46s │\n" " 2" "${symbols[${STATUS[1]}]}" "Check git status / auto-commit"
    printf "│ %s │ ${colors[${STATUS[2]}]}%-8s${reset}   │ %-46s │\n" " 3" "${symbols[${STATUS[2]}]}" "Clean dist/ directory"
    printf "│ %s │ ${colors[${STATUS[3]}]}%-8s${reset}   │ %-46s │\n" " 4" "${symbols[${STATUS[3]}]}" "Bump version (patch) and push tags"
    printf "│ %s │ ${colors[${STATUS[4]}]}%-8s${reset}   │ %-46s │\n" " 5" "${symbols[${STATUS[4]}]}" "Build package with uv"
    printf "│ %s │ ${colors[${STATUS[5]}]}%-8s${reset}   │ %-46s │\n" " 6" "${symbols[${STATUS[5]}]}" "Publish to PyPI"
    printf "│ %s │ ${colors[${STATUS[6]}]}%-8s${reset}   │ %-46s │\n" " 7" "${symbols[${STATUS[6]}]}" "Install/upgrade with uv tool"
    printf "├────┴──────────┴────────────────────────────────────────────────┤\n"
    printf "│  PROGRESS: [%s] %3d%%               │\n" "$bar" "$progress"
    printf "│         ☑ %d done  ☒ %d failed  ⊘ %d N/A                          │\n" "$completed" "$failed" "$unavailable"
    printf "├────────────────────────────────────────────────────────────────┤\n"
    printf "│  COMMANDS: [a] Run all  [r] Reset  [q] Quit  [1-7] Step        │\n"
    printf "└────────────────────────────────────────────────────────────────┘\n"
    printf "\n"
    printf "Press a key: "
}

# Run all actions in order
run_all() {
    action_1_convert_readme
    echo ""
    action_2_git_check
    echo ""
    action_3_clean_dist
    echo ""
    action_4_bump_version
    echo ""
    action_5_build
    echo ""
    action_6_publish
    echo ""
    action_7_install
}

# Reset all status
reset_status() {
    STATUS=(0 0 0 0 0 0 0)
    check_prerequisites
}

# Main loop
while true; do
    show_menu
    read -n 1 -r key
    echo ""
    echo ""

    case $key in
        1) action_1_convert_readme ;;
        2) action_2_git_check ;;
        3) action_3_clean_dist ;;
        4) action_4_bump_version ;;
        5) action_5_build ;;
        6) action_6_publish ;;
        7) action_7_install ;;
        a|A)
            echo "🚀 Running all steps in sequence..."
            echo ""
            run_all
            echo ""
            echo "Press any key to continue..."
            read -n 1 -r
            ;;
        r|R)
            reset_status
            echo "🔄 All status reset to pending"
            sleep 1
            continue
            ;;
        q|Q)
            echo "👋 Exiting..."
            exit 0
            ;;
        *)
            echo "❌ Invalid option: '$key'"
            sleep 1
            continue
            ;;
    esac

    echo ""
    echo "Press any key to continue..."
    read -n 1 -r
done
