#!/bin/bash
#
# Post-push release pipeline (called by pre-push after push completes)
#
# Architecture:
#   codebase/          ← development work (may have uncommitted changes)
#   codebase-release/  ← clean clone for builds/deploys
#
# Flow:
#   1. git push on codebase main (already done)
#   2. cd codebase-release && git pull (gets only committed code)
#   3. Increment version, create tag
#   4. Build changed components
#   5. Deploy to VPS
#   6. Push tags to gitlab
#
# This ensures only COMMITTED code gets deployed.
#
# Usage:
#   ./post-push              # Run full pipeline
#   ./post-push --dry-run    # Show what would happen
#

set -e

# Parse arguments
DRY_RUN=false
if [[ "$1" == "--dry-run" ]] || [[ "$1" == "-n" ]]; then
    DRY_RUN=true
fi

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CODEBASE_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PLATFORM_ROOT="$(cd "$CODEBASE_ROOT/.." && pwd)"
RELEASES_ROOT="$PLATFORM_ROOT/codebase-release"
INFRA_SCRIPTS="$PLATFORM_ROOT/infrastructure/scripts"
LIB_DIR="$INFRA_SCRIPTS/lib"

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

log_header() { echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"; echo -e "${CYAN}  $1${NC}"; echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"; }
log_step() { echo -e "\n${BLUE}▶${NC} $1"; }
log_info() { echo -e "  ${BLUE}ℹ${NC} $1"; }
log_success() { echo -e "  ${GREEN}✓${NC} $1"; }
log_warn() { echo -e "  ${YELLOW}⚠${NC} $1"; }
log_error() { echo -e "  ${RED}✗${NC} $1"; }
log_dry() { echo -e "  ${MAGENTA}[DRY-RUN]${NC} $1"; }

# Wrapper for commands that should be skipped in dry-run
run_cmd() {
    if [[ "$DRY_RUN" == "true" ]]; then
        log_dry "Would run: $*"
        return 0
    fi
    "$@"
}

if [[ "$DRY_RUN" == "true" ]]; then
    log_header "Lilith Platform Release Pipeline (DRY RUN)"
    log_warn "DRY RUN MODE - No changes will be made"
else
    log_header "Lilith Platform Release Pipeline"
fi

# =============================================================================
# STEP 0: Verify codebase-release exists
# =============================================================================
if [[ ! -d "$RELEASES_ROOT" ]]; then
    log_error "codebase-release/ not found at: $RELEASES_ROOT"
    log_info "Create it with: git clone codebase codebase-release"
    exit 1
fi

# =============================================================================
# STEP 1: Pull latest from codebase into codebase-release
# =============================================================================
log_step "Pulling latest from codebase into codebase-release..."

cd "$RELEASES_ROOT"
log_info "Working directory: $RELEASES_ROOT"

# Fetch from codebase (origin)
run_cmd git fetch origin main

# Show what would be pulled
COMMITS_TO_PULL=$(git log HEAD..origin/main --oneline 2>/dev/null | wc -l)
if [[ "$COMMITS_TO_PULL" -eq 0 ]]; then
    log_info "Already up to date with codebase"
else
    log_info "$COMMITS_TO_PULL new commit(s) from codebase"
    git log HEAD..origin/main --oneline | head -5
fi

# Pull changes
run_cmd git pull origin main

log_success "Synced with codebase"

# =============================================================================
# STEP 2: Increment version and tag
# =============================================================================
log_step "Incrementing version..."

# VERSION.json is in codebase-release (we're already cd'd there)
VERSION_FILE="$RELEASES_ROOT/VERSION.json"

if [[ ! -f "$VERSION_FILE" ]]; then
    log_warn "VERSION.json not found, creating..."
    echo '{"major": 0, "merges": 0, "builds": 0, "version": "0.0.0"}' > "$VERSION_FILE"
fi

# Calculate next version
CURRENT_VERSION=$(jq -r '.version' "$VERSION_FILE")
MAJOR=$(jq -r '.major' "$VERSION_FILE")
MERGES=$(jq -r '.merges' "$VERSION_FILE")
BUILDS=$(jq -r '.builds' "$VERSION_FILE")
NEXT_BUILD=$((BUILDS + 1))
NEW_VERSION="$MAJOR.$MERGES.$NEXT_BUILD"

log_info "Current: $CURRENT_VERSION"
log_info "Next:    $NEW_VERSION"

if [[ "$DRY_RUN" != "true" ]]; then
    # Update VERSION.json
    jq --arg v "$NEW_VERSION" \
       --argjson builds "$NEXT_BUILD" \
       --arg lastBuild "$(date -Iseconds)" \
       '.builds = $builds | .version = $v | .lastBuild = $lastBuild' \
       "$VERSION_FILE" > "$VERSION_FILE.tmp" && mv "$VERSION_FILE.tmp" "$VERSION_FILE"

    git add VERSION.json
    git commit -m "build: v$NEW_VERSION

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>"
    git tag -a "v$NEW_VERSION" -m "Release v$NEW_VERSION"
else
    log_dry "Would increment VERSION.json builds: $NEXT_BUILD"
    log_dry "Would commit version bump"
    log_dry "Would create tag: v$NEW_VERSION"
fi

log_success "Version: $NEW_VERSION"

# =============================================================================
# STEP 3: Detect and build changed components
# =============================================================================
log_step "Detecting changed components..."

# Source change detection if available
if [[ -f "$LIB_DIR/detect-changes.sh" ]]; then
    source "$LIB_DIR/detect-changes.sh"
fi

LAST_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
CHANGED_SERVICES=""

if [[ -n "$LAST_TAG" ]] && type detect_changed_services &>/dev/null; then
    CHANGED_SERVICES=$(detect_changed_services "$LAST_TAG" 2>/dev/null || echo "")
fi

if [[ -z "$CHANGED_SERVICES" ]]; then
    log_info "Checking file patterns for changes..."

    # Fallback: check all commits since last tag (excludes version bump)
    if [[ -n "$LAST_TAG" ]]; then
        CHANGED_FILES=$(git diff --name-only ${LAST_TAG}..HEAD~1 2>/dev/null || echo "")
    else
        CHANGED_FILES=$(git diff --name-only HEAD~1 2>/dev/null || echo "")
    fi

    if echo "$CHANGED_FILES" | grep -q "features/status-dashboard/"; then
        CHANGED_SERVICES="status-dashboard"
    fi

    if echo "$CHANGED_FILES" | grep -q "infrastructure/service-registry/"; then
        CHANGED_SERVICES="$CHANGED_SERVICES service-registry"
    fi

    # Conversation Assistant - detect which component changed
    if echo "$CHANGED_FILES" | grep -q "features/conversation-assistant/macos/"; then
        CHANGED_SERVICES="$CHANGED_SERVICES conversation-assistant-macos"
    fi
    if echo "$CHANGED_FILES" | grep -qE "features/conversation-assistant/(server|frontend|infrastructure)/"; then
        CHANGED_SERVICES="$CHANGED_SERVICES conversation-assistant-server"
    fi
fi

if [[ -z "$CHANGED_SERVICES" ]]; then
    log_info "No deployable changes detected"
else
    log_info "Changed services: $CHANGED_SERVICES"

    # Build and deploy each service using infrastructure scripts
    for SERVICE in $CHANGED_SERVICES; do
        case "$SERVICE" in
            status-dashboard)
                log_step "Deploying status-dashboard..."
                run_cmd "$INFRA_SCRIPTS/deploy-status-dashboard.sh" || log_warn "status-dashboard deploy failed"
                ;;
            service-registry)
                log_step "Deploying service-registry..."
                run_cmd "$INFRA_SCRIPTS/deploy-service-registry.sh" || log_warn "service-registry deploy failed"
                ;;
            conversation-assistant-macos)
                log_step "Deploying conversation-assistant macOS app to plum..."
                run_cmd "$CODEBASE_ROOT/features/conversation-assistant/macos/deploy-remote.sh" || log_warn "conversation-assistant-macos deploy failed"
                ;;
            conversation-assistant-server)
                log_step "Deploying conversation-assistant server..."
                run_cmd "$INFRA_SCRIPTS/deploy-conversation-assistant.sh" || log_warn "conversation-assistant-server deploy failed"
                ;;
            *)
                log_warn "Unknown service: $SERVICE (skipping)"
                ;;
        esac
    done
fi

# =============================================================================
# STEP 4: Push tags to gitlab
# =============================================================================
log_step "Pushing to gitlab..."

run_cmd git push gitlab main --tags || log_warn "Push to gitlab failed"

log_success "Pushed to gitlab"

# =============================================================================
# STEP 5: Sync version back to codebase
# =============================================================================
log_step "Syncing version back to codebase..."

cd "$CODEBASE_ROOT"
log_info "Working directory: $CODEBASE_ROOT"

# Pull the version commit from codebase-release
run_cmd git fetch "$RELEASES_ROOT" main
run_cmd git merge FETCH_HEAD --ff-only || {
    log_warn "Could not fast-forward merge, manual sync needed"
    log_info "Run: cd codebase && git pull ../codebase-release main"
}

log_success "Codebase synced with version $NEW_VERSION"

# =============================================================================
# DONE
# =============================================================================
if [[ "$DRY_RUN" == "true" ]]; then
    log_header "DRY RUN Complete"
    log_info "No changes were made"
    log_info "Run without --dry-run to execute"
else
    log_header "Release v$NEW_VERSION Complete"
    log_info "Codebase VERSION.json updated"
    log_info "Tag v$NEW_VERSION pushed to gitlab"
fi

exit 0
