#!/bin/bash

# Event Miner Build Script
# Provides convenient build targets with automatic version management
# Automatically increments patch version with each build

set -e  # Exit on any error

# Project configuration
PROJECT_NAME="event_miner"
PROJECT_NAME_UPPER="EVENT_MINER"
MAIN_BINARY="event_miner"
SRC_DIR="."

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to automatically increment version
increment_version() {
    print_status "Incrementing version..."
    
    # Check if we're in a git repository
    if ! git rev-parse --git-dir > /dev/null 2>&1; then
        print_warning "Not in a git repository - skipping version increment"
        return 0
    fi
    
    # Get the highest version tag (not necessarily the most recent chronologically)
    LATEST_TAG=$(git tag -l 'v*.*.*' | sort -V | tail -n 1 || echo "v0.1.0")
    if [[ -z "$LATEST_TAG" ]]; then
        LATEST_TAG="v0.1.0"
    fi
    
    # Extract version components (remove 'v' prefix if present)
    VERSION=${LATEST_TAG#v}
    
    # Parse major.minor.patch
    if [[ $VERSION =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
        MAJOR=${BASH_REMATCH[1]}
        MINOR=${BASH_REMATCH[2]}
        PATCH=${BASH_REMATCH[3]}
    else
        print_error "Invalid version format in tag: $LATEST_TAG"
        print_error "Expected format: v0.1.0"
        return 1
    fi
    
    # Increment patch version
    NEW_PATCH=$((PATCH + 1))
    NEW_VERSION="v${MAJOR}.${MINOR}.${NEW_PATCH}"
    
    print_status "Current version: $LATEST_TAG"
    print_status "New version: $NEW_VERSION"
    
    # Create new git tag
    if git tag "$NEW_VERSION" 2>/dev/null; then
        print_success "Created new version tag: $NEW_VERSION"
    else
        print_warning "Tag $NEW_VERSION already exists - using existing version"
        NEW_VERSION=$LATEST_TAG
    fi
    
    # Update VERSION file for compatibility
    echo "${NEW_VERSION#v}" > VERSION
    print_success "Updated VERSION file to ${NEW_VERSION#v}"
}

# Function to show usage
show_usage() {
    echo "Event Miner Build Script"
    echo "========================"
    echo ""
    echo "Usage: $0 [target] [-m \"commit message\"]"
    echo ""
    echo "Available targets:"
    echo "  clean       - Clean all build artifacts"
    echo "  build       - Build event_miner binary (default)"
    echo "  test        - Run tests"
    echo "  install     - Install event_miner to /usr/local/bin"
    echo "  uninstall   - Remove event_miner from /usr/local/bin"
    echo "  help        - Show this help message"
    echo ""
    echo "Options:"
    echo "  -m \"message\" - Commit message (recommended for documentation)"
    echo ""
    echo "Binary output: $MAIN_BINARY"
    echo "Source files: event_miner.c"
    echo ""
    echo "Note: Each build automatically increments the patch version,"
    echo "      creates git tags, and updates the VERSION file."
}

# Parse command line arguments
COMMIT_MESSAGE=""
TARGET=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -m)
            COMMIT_MESSAGE="$2"
            shift 2
            ;;
        clean|build|lib|examples|test|install|uninstall|help|--help|-h)
            TARGET="$1"
            shift
            ;;
        *)
            if [[ -z "$TARGET" ]]; then
                TARGET="$1"
            else
                print_error "Unknown option: $1"
                show_usage
                exit 1
            fi
            shift
            ;;
    esac
done

# Set default target
TARGET=${TARGET:-build}

# Handle targets
case "$TARGET" in
    clean)
        print_status "Cleaning build artifacts..."
        if [[ -f "Makefile" ]]; then
            make clean
        else
            rm -f *.a *.so *.o "$MAIN_BINARY"
            rm -f "${SRC_DIR}/version.h" "${SRC_DIR}/version.c"
        fi
        print_success "Clean completed"
        ;;
        
    build)
        if [[ -n "$COMMIT_MESSAGE" ]]; then
            print_status "Build message: $COMMIT_MESSAGE"
        fi
        
        increment_version
        print_status "Building $MAIN_BINARY..."
        
        if [[ -f "Makefile" ]]; then
            make clean
            make
        else
            print_error "No Makefile found. Please create a Makefile for your project."
            print_error "The build script works as a wrapper around make."
            exit 1
        fi
        
        # Check if binary was built
        if [[ -f "$MAIN_BINARY" ]]; then
            SIZE=$(stat -c%s "$MAIN_BINARY" 2>/dev/null || stat -f%z "$MAIN_BINARY" 2>/dev/null || echo "unknown")
            print_success "Event miner built successfully (${SIZE} bytes)"
            ls -la "$MAIN_BINARY"
            
            # Commit and push changes if we have a commit message and we're in a git repository
            if [[ -n "$COMMIT_MESSAGE" ]] && git rev-parse --git-dir > /dev/null 2>&1; then
                print_status "Adding changes to git..."
                git add .
                
                print_status "Committing changes..."
                git commit -m "$COMMIT_MESSAGE"
                print_success "Changes committed with message: $COMMIT_MESSAGE"
                
                print_status "Pushing to remote repository..."
                git push origin HEAD && git push --tags
                print_success "Changes and tags pushed to remote repository"
            fi
        else
            print_error "Failed to build $MAIN_BINARY binary"
            exit 1
        fi
        ;;
        
    examples)
        if [[ ! -d "examples" ]]; then
            print_error "No examples/ directory found"
            exit 1
        fi
        
        increment_version
        print_status "Building examples..."
        
        if [[ -f "Makefile" ]]; then
            make clean
            make
            if make examples 2>/dev/null; then
                print_success "Examples built successfully"
                ls -la examples/
            else
                print_warning "Examples target not found in Makefile"
            fi
        else
            print_error "No Makefile found for building examples"
            exit 1
        fi
        ;;
        
    test)
        print_status "Running tests..."
        
        if [[ -f "Makefile" ]]; then
            make clean
            make
            if make test 2>/dev/null; then
                print_success "All tests passed"
            else
                print_warning "Test target not found in Makefile, checking tests/ directory"
                if [[ -d "tests" ]]; then
                    cd tests && make test 2>/dev/null && cd ..
                    print_success "Tests completed"
                else
                    print_error "No tests found"
                    exit 1
                fi
            fi
        else
            print_error "No Makefile found for running tests"
            exit 1
        fi
        ;;

    install)
        increment_version
        print_status "Installing library to system..."
        
        if [[ -f "Makefile" ]]; then
            make clean
            make
            sudo make install
            print_success "Library installed to /usr/local"
        else
            print_error "No Makefile found for installation"
            exit 1
        fi
        ;;
        
    uninstall)
        print_status "Uninstalling library from system..."
        
        if [[ -f "Makefile" ]]; then
            sudo make uninstall
            print_success "Library uninstalled"
        else
            print_error "No Makefile found for uninstallation"
            exit 1
        fi
        ;;
        
    help|--help|-h)
        show_usage
        ;;
        
    *)
        print_error "Unknown target: $TARGET"
        echo ""
        show_usage
        exit 1
        ;;
esac
