#!/bin/bash
set -euo pipefail

# Codex Memory Build Pipeline
# Simple build script for the memory storage service

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

# Build configuration
BUILD_MODE="${BUILD_MODE:-release}"
VERIFY_BUILD="${VERIFY_BUILD:-true}"
INSTALL_LOCAL="${INSTALL_LOCAL:-false}"

print_banner() {
    echo -e "${BLUE}=================================${NC}"
    echo -e "${BLUE}  Codex Memory Build Pipeline (v2.1.0)  ${NC}"
    echo -e "${BLUE}=================================${NC}"
    echo ""
}

print_config() {
    echo -e "${YELLOW}Build Configuration:${NC}"
    echo "  Build Mode: $BUILD_MODE"
    echo "  Project: codex-memory (storage service)"
    echo "  Verify Build: $VERIFY_BUILD"
    echo "  Install Local: $INSTALL_LOCAL"
    echo ""
}

check_prerequisites() {
    echo -e "${BLUE}Checking prerequisites...${NC}"
    
    # Check Cargo
    if ! command -v cargo &> /dev/null; then
        echo -e "${RED}Error: cargo not found. Please install Rust.${NC}"
        exit 1
    fi
    
    # Check for required environment
    if [[ ! -f "Cargo.toml" ]]; then
        echo -e "${RED}Error: Cargo.toml not found. Run from project root.${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}Prerequisites OK${NC}"
    echo ""
}

build_basic() {
    echo -e "${BLUE}Building codex-memory...${NC}"
    
    if cargo build "--${BUILD_MODE}"; then
        echo -e "${GREEN}Build successful${NC}"
        
        # Check binary size
        if [[ -f "target/${BUILD_MODE}/codex-memory" ]]; then
            local size=$(du -h "target/${BUILD_MODE}/codex-memory" | cut -f1)
            echo "  Binary size: $size"
        fi
    else
        echo -e "${RED}Build failed${NC}"
        exit 1
    fi
    echo ""
}

run_build_tests() {
    echo -e "${BLUE}Running build verification tests...${NC}"
    
    if cargo test --test build_system_test; then
        echo -e "${GREEN}Build tests passed${NC}"
    else
        echo -e "${RED}Build tests failed${NC}"
        exit 1
    fi
    echo ""
}

install_locally() {
    echo -e "${BLUE}Installing codex-memory locally...${NC}"
    
    if cargo install --path . --force; then
        echo -e "${GREEN}Local installation successful${NC}"
        
        # Verify installation
        if command -v codex-memory &> /dev/null; then
            echo "  Installation location: $(which codex-memory)"
            echo "  Version: $(codex-memory --version 2>/dev/null || echo 'Version check failed')"
        fi
    else
        echo -e "${RED}Local installation failed${NC}"
        exit 1
    fi
    echo ""
}

show_build_artifacts() {
    echo -e "${BLUE}Build artifacts summary:${NC}"
    
    if [[ -d "target/${BUILD_MODE}" ]]; then
        echo "  Target directory: target/${BUILD_MODE}/"
        
        if [[ -f "target/${BUILD_MODE}/codex-memory" ]]; then
            local size=$(du -h "target/${BUILD_MODE}/codex-memory" | cut -f1)
            local timestamp=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "target/${BUILD_MODE}/codex-memory")
            echo "  Binary: codex-memory ($size, built $timestamp)"
        fi
        
        # Show dependency count in deps/
        if [[ -d "target/${BUILD_MODE}/deps" ]]; then
            local dep_count=$(find "target/${BUILD_MODE}/deps" -name "*.rlib" | wc -l | tr -d ' ')
            echo "  Dependencies: $dep_count .rlib files"
        fi
    fi
    echo ""
}

clean_if_requested() {
    if [[ "${CLEAN_FIRST:-false}" == "true" ]]; then
        echo -e "${BLUE}Cleaning previous build artifacts...${NC}"
        cargo clean
        echo -e "${GREEN}Clean complete${NC}"
        echo ""
    fi
}

main() {
    print_banner
    print_config
    check_prerequisites
    clean_if_requested
    
    # Simple build - no features
    build_basic
    
    if [[ "$VERIFY_BUILD" == "true" ]]; then
        run_build_tests
    fi
    
    if [[ "$INSTALL_LOCAL" == "true" ]]; then
        install_locally
    fi
    
    show_build_artifacts
    
    echo -e "${GREEN}Build pipeline completed successfully!${NC}"
}

# Help function
show_help() {
    echo "Codex Memory Build Pipeline - Simple Storage Service"
    echo ""
    echo "Usage: $0 [options]"
    echo ""
    echo "Environment Variables:"
    echo "  BUILD_MODE=release|debug     Build mode (default: release)"
    echo "  VERIFY_BUILD=true            Run build verification tests"
    echo "  INSTALL_LOCAL=true           Install binary locally"
    echo "  CLEAN_FIRST=true             Clean before building"
    echo ""
    echo "  # Note: codex-dreams is now a separate project at"
    echo "  # https://github.com/Ladvien/codex-dreams"
    echo ""
    echo "Examples:"
    echo "  # Basic build"
    echo "  ./scripts/build.sh"
    echo ""
    echo "  # Build with local installation"
    echo "  INSTALL_LOCAL=true ./scripts/build.sh"
    echo ""
    echo "  # Debug build"
    echo "  BUILD_MODE=debug ./scripts/build.sh"
    echo ""
    echo "  # Clean build with verification"
    echo "  CLEAN_FIRST=true VERIFY_BUILD=true ./scripts/build.sh"
}

# Check for help flag
if [[ "${1:-}" == "--help" ]] || [[ "${1:-}" == "-h" ]]; then
    show_help
    exit 0
fi

# Run main function
main "$@"