#!/bin/bash
# RSSuper Common Build Utilities
# Shared functions used across all platform build scripts

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

# Logging functions
log_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

log_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

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

log_error() {
    echo -e "${RED}❌ $1${NC}"
}

# Get project root directory
get_project_root() {
    echo "$(cd "$(dirname "$0")/.." && pwd)"
}

# Get current timestamp in ISO format
get_timestamp() {
    date -u "+%Y-%m-%dT%H:%M:%SZ"
}

# Get human-readable timestamp
get_timestamp_human() {
    date -u "+%Y-%m-%d %H:%M:%S UTC"
}

# Get current git commit hash
get_git_commit() {
    git rev-parse HEAD 2>/dev/null || echo "unknown"
}

# Get short git commit hash
get_git_commit_short() {
    local commit=$(get_git_commit)
    echo ${commit:0:7}
}

# Get current git branch
get_git_branch() {
    git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown"
}

# Get git status (clean or modified)
get_git_status() {
    if git diff --quiet 2>/dev/null && git diff --cached --quiet 2>/dev/null; then
        echo "clean"
    else
        echo "modified"
    fi
}

# Check if running in CI
is_ci() {
    [ -n "$CI" ]
}

# Check if command exists
command_exists() {
    command -v "$1" &> /dev/null
}

# Create a temporary file with cleanup trap
create_temp_file() {
    local temp_file=$(mktemp)
    trap "rm -f '$temp_file'" EXIT
    echo "$temp_file"
}

# Parse command line arguments
# Usage: parse_args "option1:value1 option2:value2" 
# Sets variables OPTION1, OPTION2 with values
parse_args() {
    local options="$1"
    shift
    
    for opt in $options; do
        local key=${opt%%:*}
        local value=${opt#*:}
        export "$key=$value"
    done
}

# Show spinner while command runs (for nice UX)
run_with_spinner() {
    local message="$1"
    shift
    
    echo -e "${BLUE}$message...${NC}"
    "$@"
}

# Generate a build report
generate_build_report() {
    local platform="$1"
    local status="$2"
    local details="$3"
    
    local report_file="${platform}-build-report.md"
    local timestamp=$(get_timestamp_human)
    local commit=$(get_git_commit_short)
    local branch=$(get_git_branch)
    
    {
        echo "# $platform Build Report"
        echo ""
        echo "| | |"
        echo "|---|---|"
        echo "| **Status** | $status |"
        echo "| **Commit** | \`$commit\` |"
        echo "| **Branch** | \`$branch\` |"
        echo "| **Time** | $timestamp |"
        echo ""
        
        if [ "$status" = "FAILED" ]; then
            echo "## Errors"
            echo ""
            echo "$details"
        else
            echo "## Result"
            echo ""
            echo "$platform build completed successfully."
        fi
    } > "$report_file"
    
    echo "Build report written to: $report_file"
}

# Wait for user input (useful for debugging)
wait_for_input() {
    echo "Press Enter to continue..."
    read
}

# Export for use in other scripts
export -f log_info
export -f log_success
export -f log_warning
export -f log_error
export -f get_project_root
export -f get_timestamp
export -f get_timestamp_human
export -f get_git_commit
export -f get_git_commit_short
export -f get_git_branch
export -f get_git_status
export -f is_ci
export -f command_exists
export -f create_temp_file
export -f parse_args
export -f run_with_spinner
export -f generate_build_report
export -f wait_for_input
