#!/bin/bash

# TankStopp Build Script
# This script handles templ generation and application building

set -e

# 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 check if templ is installed
check_templ() {
    if ! command -v templ &> /dev/null; then
        print_error "templ CLI is not installed"
        print_status "Installing templ..."
        go install github.com/a-h/templ/cmd/templ@latest
        if [ $? -eq 0 ]; then
            print_success "templ installed successfully"
        else
            print_error "Failed to install templ"
            exit 1
        fi
    else
        print_success "templ CLI is available"
    fi
}

# Function to format templ files
format_templ() {
    print_status "Formatting templ files..."
    templ fmt ./internal/views/
    if [ $? -eq 0 ]; then
        print_success "Templ files formatted successfully"
    else
        print_error "Failed to format templ files"
        exit 1
    fi
}

# Function to generate Go code from templ files
generate_templ() {
    print_status "Generating Go code from templ files..."
    templ generate ./internal/views/
    if [ $? -eq 0 ]; then
        print_success "Go code generated successfully"
    else
        print_error "Failed to generate Go code from templ files"
        exit 1
    fi
}

# Function to build the application
build_app() {
    print_status "Building application..."
    go build -o tankstopp ./cmd/main.go
    if [ $? -eq 0 ]; then
        print_success "Application built successfully"
    else
        print_error "Failed to build application"
        exit 1
    fi
}

# Function to run tests
run_tests() {
    print_status "Running tests..."
    go test ./...
    if [ $? -eq 0 ]; then
        print_success "All tests passed"
    else
        print_error "Some tests failed"
        exit 1
    fi
}

# Function to clean generated files
clean() {
    print_status "Cleaning generated files..."
    find ./internal/views -name "*_templ.go" -delete
    rm -f tankstopp
    print_success "Cleaned generated files"
}

# Function to watch for changes (development mode)
watch() {
    print_status "Starting development watch mode..."
    print_warning "This requires 'entr' to be installed (brew install entr / apt-get install entr)"

    if ! command -v entr &> /dev/null; then
        print_error "entr is not installed. Install it with: brew install entr (macOS) or apt-get install entr (Linux)"
        exit 1
    fi

    print_status "Watching for changes in templ files..."
    find ./internal/views -name "*.templ" | entr -r sh -c 'echo "Changes detected, rebuilding..." && ./scripts/build.sh dev'
}

# Function to show help
show_help() {
    echo "TankStopp Build Script"
    echo ""
    echo "Usage: $0 [COMMAND]"
    echo ""
    echo "Commands:"
    echo "  dev         - Development build (format, generate, build)"
    echo "  prod        - Production build (format, generate, test, build)"
    echo "  generate    - Generate Go code from templ files only"
    echo "  format      - Format templ files only"
    echo "  clean       - Clean generated files"
    echo "  test        - Run tests only"
    echo "  watch       - Watch for changes and rebuild (requires entr)"
    echo "  help        - Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 dev      # Quick development build"
    echo "  $0 prod     # Production build with tests"
    echo "  $0 watch    # Watch mode for development"
}

# Main script logic
main() {
    case "${1:-dev}" in
        "dev")
            print_status "Starting development build..."
            check_templ
            format_templ
            generate_templ
            build_app
            print_success "Development build completed!"
            ;;
        "prod")
            print_status "Starting production build..."
            check_templ
            format_templ
            generate_templ
            run_tests
            build_app
            print_success "Production build completed!"
            ;;
        "generate")
            print_status "Generating templ files..."
            check_templ
            generate_templ
            print_success "Generation completed!"
            ;;
        "format")
            print_status "Formatting templ files..."
            check_templ
            format_templ
            print_success "Formatting completed!"
            ;;
        "clean")
            clean
            ;;
        "test")
            run_tests
            ;;
        "watch")
            watch
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            print_error "Unknown command: $1"
            show_help
            exit 1
            ;;
    esac
}

# Check if we're in the right directory
if [ ! -f "go.mod" ]; then
    print_error "This script must be run from the project root directory"
    exit 1
fi

# Run main function with all arguments
main "$@"
