#!/bin/bash
# 🚀 NETGESCON - WORKFLOW GIT DISTRIBUITO
# Creato: 19/07/2025 - Workflow Michele + AI

set -e

echo "🚀 === NETGESCON - WORKFLOW GIT DISTRIBUITO ==="
echo "📅 $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# === CONFIGURAZIONI ===
CURRENT_BRANCH=$(git branch --show-current)
VERSION_FILE="docs/versione/VERSION.txt"
CHANGELOG_FILE="docs/versione/CHANGELOG.md"

# === FUNZIONI ===

# Funzione per incrementare versione
increment_version() {
    local version_type=$1
    
    if [ ! -f "$VERSION_FILE" ]; then
        echo "1.0.0" > "$VERSION_FILE"
        echo "   ✅ File versione creato: 1.0.0"
        return
    fi
    
    local current_version=$(cat "$VERSION_FILE")
    local major=$(echo $current_version | cut -d. -f1)
    local minor=$(echo $current_version | cut -d. -f2)
    local patch=$(echo $current_version | cut -d. -f3)
    
    case $version_type in
        "major")
            major=$((major + 1))
            minor=0
            patch=0
            ;;
        "minor")
            minor=$((minor + 1))
            patch=0
            ;;
        "patch")
            patch=$((patch + 1))
            ;;
    esac
    
    local new_version="$major.$minor.$patch"
    echo "$new_version" > "$VERSION_FILE"
    echo "   ✅ Versione aggiornata: $current_version → $new_version"
}

# Funzione per aggiornare changelog
update_changelog() {
    local version=$1
    local description="$2"
    
    # Crea changelog se non existe
    if [ ! -f "$CHANGELOG_FILE" ]; then
        cat > "$CHANGELOG_FILE" << 'EOF'
# 📋 NETGESCON - CHANGELOG

Tutte le modifiche importanti al progetto NetGescon sono documentate in questo file.

Il formato è basato su [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
e questo progetto aderisce al [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

---

EOF
    fi
    
    # Aggiunge nuova entry in cima
    local temp_file=$(mktemp)
    local current_date=$(date '+%Y-%m-%d')
    
    # Header del file
    head -n 8 "$CHANGELOG_FILE" > "$temp_file"
    
    # Nuova entry
    cat >> "$temp_file" << EOF

## [${version}] - ${current_date}

### Added
- ${description}

EOF
    
    # Resto del file
    tail -n +9 "$CHANGELOG_FILE" >> "$temp_file"
    
    mv "$temp_file" "$CHANGELOG_FILE"
    echo "   ✅ Changelog aggiornato"
}

# === COMANDI PRINCIPALI ===

case "${1:-help}" in

    # === SVILUPPO ===
    "dev-start")
        echo "🌿 Inizio sviluppo feature..."
        
        if [ -z "$2" ]; then
            echo "❌ Specificare nome feature: $0 dev-start nome-feature"
            exit 1
        fi
        
        feature_name="$2"
        branch_name="feature/$feature_name"
        
        git checkout development
        git pull origin development
        git checkout -b "$branch_name"
        
        echo "   ✅ Branch creato: $branch_name"
        echo "   📝 Ora puoi sviluppare la feature '$feature_name'"
        ;;

    "dev-commit")
        echo "📦 Commit sviluppo..."
        
        if [ -z "$2" ]; then
            echo "❌ Specificare messaggio: $0 dev-commit 'messaggio'"
            exit 1
        fi
        
        git add .
        git commit -m "🚧 $2

📍 Branch: $CURRENT_BRANCH
🔄 Sviluppo in corso
📅 $(date '+%Y-%m-%d %H:%M:%S')"
        
        echo "   ✅ Commit creato sul branch $CURRENT_BRANCH"
        ;;

    "dev-finish")
        echo "🎯 Finalizzazione feature..."
        
        if [[ ! "$CURRENT_BRANCH" =~ ^feature/ ]]; then
            echo "❌ Devi essere su un branch feature/"
            exit 1
        fi
        
        feature_name=$(echo "$CURRENT_BRANCH" | sed 's/feature\///')
        
        # Push del branch
        git push origin "$CURRENT_BRANCH"
        
        # Merge in development
        git checkout development
        git pull origin development
        git merge --no-ff "$CURRENT_BRANCH" -m "✅ Feature completata: $feature_name

📋 Merge feature/$feature_name in development
🎯 Feature pronta per testing
📅 $(date '+%Y-%m-%d %H:%M:%S')"
        
        # Pulizia
        git branch -d "$CURRENT_BRANCH"
        git push origin --delete "$CURRENT_BRANCH"
        git push origin development
        
        echo "   ✅ Feature '$feature_name' integrata in development"
        ;;

    # === RELEASE ===
    "release-start")
        echo "🚀 Inizio preparazione release..."
        
        version_type="${2:-patch}"
        
        git checkout development
        git pull origin development
        git checkout release
        git pull origin release
        git merge --no-ff development -m "🔄 Merge development in release per nuova versione"
        
        # Incrementa versione
        increment_version "$version_type"
        new_version=$(cat "$VERSION_FILE")
        
        # Aggiorna changelog
        update_changelog "$new_version" "Nuova release con feature sviluppate"
        
        # Commit versione
        git add "$VERSION_FILE" "$CHANGELOG_FILE"
        git commit -m "🏷️ Bump versione a $new_version

📋 Preparazione release $new_version
🔄 Changelog aggiornato
📅 $(date '+%Y-%m-%d %H:%M:%S')"
        
        git push origin release
        
        echo "   ✅ Release $new_version preparata"
        ;;

    "release-deploy")
        echo "🚀 Deploy release in produzione..."
        
        if [ "$CURRENT_BRANCH" != "release" ]; then
            echo "❌ Devi essere sul branch release"
            exit 1
        fi
        
        current_version=$(cat "$VERSION_FILE")
        
        # Merge in master
        git checkout master
        git pull origin master
        git merge --no-ff release -m "🎯 Release $current_version in produzione

📋 Deploy versione $current_version
✅ Testing completato
📅 $(date '+%Y-%m-%d %H:%M:%S')"
        
        # Tag versione
        git tag -a "v$current_version" -m "🏷️ Release $current_version

📋 Versione stabile per produzione
🎯 Tag: v$current_version
📅 $(date '+%Y-%m-%d %H:%M:%S')"
        
        # Push tutto
        git push origin master
        git push origin "v$current_version"
        
        # Merge master in development
        git checkout development
        git merge master
        git push origin development
        
        echo "   ✅ Release $current_version deployata in produzione"
        echo "   🏷️ Tag creato: v$current_version"
        ;;

    # === HOTFIX ===
    "hotfix-start")
        echo "🚨 Inizio hotfix urgente..."
        
        if [ -z "$2" ]; then
            echo "❌ Specificare nome hotfix: $0 hotfix-start nome-hotfix"
            exit 1
        fi
        
        hotfix_name="$2"
        branch_name="hotfix/$hotfix_name"
        
        git checkout master
        git pull origin master
        git checkout -b "$branch_name"
        
        echo "   ✅ Branch hotfix creato: $branch_name"
        ;;

    "hotfix-deploy")
        echo "🚨 Deploy hotfix urgente..."
        
        if [[ ! "$CURRENT_BRANCH" =~ ^hotfix/ ]]; then
            echo "❌ Devi essere su un branch hotfix/"
            exit 1
        fi
        
        hotfix_name=$(echo "$CURRENT_BRANCH" | sed 's/hotfix\///')
        
        # Incrementa patch version
        increment_version "patch"
        new_version=$(cat "$VERSION_FILE")
        
        # Aggiorna changelog
        update_changelog "$new_version" "Hotfix: $hotfix_name"
        
        # Commit versione
        git add "$VERSION_FILE" "$CHANGELOG_FILE"
        git commit -m "🚨 Hotfix $new_version: $hotfix_name

📋 Fix urgente in produzione
🔄 Versione: $new_version
📅 $(date '+%Y-%m-%d %H:%M:%S')"
        
        # Merge in master
        git checkout master
        git merge --no-ff "$CURRENT_BRANCH"
        git tag -a "v$new_version" -m "🚨 Hotfix $new_version: $hotfix_name"
        git push origin master
        git push origin "v$new_version"
        
        # Merge in development e release
        git checkout development
        git merge master
        git push origin development
        
        git checkout release
        git merge master
        git push origin release
        
        # Pulizia
        git branch -d "$CURRENT_BRANCH"
        git push origin --delete "$CURRENT_BRANCH"
        
        echo "   ✅ Hotfix $hotfix_name deployato: v$new_version"
        ;;

    # === UTILITÀ ===
    "status")
        echo "📊 Status repository NetGescon:"
        echo ""
        echo "🌿 Branch corrente: $CURRENT_BRANCH"
        echo "📋 Versione: $(cat $VERSION_FILE 2>/dev/null || echo 'Non definita')"
        echo ""
        echo "🔄 Status Git:"
        git status --short
        echo ""
        echo "🌐 Remotes:"
        git remote -v
        echo ""
        echo "🏷️ Ultimi 5 tag:"
        git tag --sort=-version:refname | head -5
        ;;

    "sync")
        echo "🔄 Sincronizzazione con server..."
        
        git fetch origin
        git status
        
        echo ""
        echo "📋 Branch disponibili:"
        git branch -a
        ;;

    "help"|*)
        echo "🛠️ === NETGESCON - WORKFLOW GIT COMANDI ==="
        echo ""
        echo "🌿 SVILUPPO:"
        echo "   $0 dev-start [nome-feature]    # Inizio nuova feature"
        echo "   $0 dev-commit [messaggio]      # Commit durante sviluppo"  
        echo "   $0 dev-finish                  # Finalizza feature"
        echo ""
        echo "🚀 RELEASE:"
        echo "   $0 release-start [major|minor|patch]  # Prepara release"
        echo "   $0 release-deploy                     # Deploy in produzione"
        echo ""
        echo "🚨 HOTFIX:"
        echo "   $0 hotfix-start [nome]         # Inizio hotfix urgente"
        echo "   $0 hotfix-deploy               # Deploy hotfix"
        echo ""
        echo "🛠️ UTILITÀ:"
        echo "   $0 status                      # Status repository"
        echo "   $0 sync                        # Sincronizza con server"
        echo "   $0 help                        # Questa guida"
        echo ""
        echo "📋 Struttura Branches:"
        echo "   master      → Produzione stabile"
        echo "   release     → Preparazione release"
        echo "   development → Integrazione feature"
        echo "   feature/*   → Sviluppo singole feature"
        echo "   hotfix/*    → Fix urgenti produzione"
        ;;

esac

echo ""
echo "📅 $(date '+%Y-%m-%d %H:%M:%S') - Operazione completata"
