#!/bin/bash

# Build verification script for Stock Bot Trading Platform

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

# Default options
VERBOSE=false

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --verbose|-v)
            VERBOSE=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [--verbose]"
            echo "  --verbose, -v  Show verbose output"
            echo "  --help, -h     Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

echo -e "${GREEN}=== Verifying Build Health ===${NC}"

errors=()
warnings=()

# Check for common build issues
echo -e "${YELLOW}Checking for common build issues...${NC}"

# Check for mismatched .d.ts files in source directories
echo -e "${BLUE}Checking for .d.ts files in source directories...${NC}"
source_dts_files=$(find ./libs/*/src -name "*.d.ts" -type f 2>/dev/null)
if [ -n "$source_dts_files" ]; then
    warnings+=("Found .d.ts files in source directories:")
    while IFS= read -r file; do
        warnings+=("  - $file")
    done <<< "$source_dts_files"
fi

# Check for missing dist directories after build
echo -e "${BLUE}Checking for missing dist directories...${NC}"
libraries=("types" "config" "logger" "utils" "cache" "http")
for lib in "${libraries[@]}"; do
    dist_path="libs/$lib/dist"
    if [ ! -d "$dist_path" ]; then
        errors+=("Missing dist directory for $lib")
    else
        index_file="$dist_path/index.js"
        if [ ! -f "$index_file" ]; then
            errors+=("Missing index.js in dist for $lib")
        fi
    fi
done

# Check for TypeScript compilation errors
echo -e "${BLUE}Checking for TypeScript compilation errors...${NC}"
tsc_errors=$(find . -name "*.tsbuildinfo" -exec grep -l "error" {} \; 2>/dev/null)
if [ -n "$tsc_errors" ]; then
    errors+=("TypeScript compilation errors found in build info files")
    if [ "$VERBOSE" = true ]; then
        while IFS= read -r file; do
            errors+=("  - $file")
        done <<< "$tsc_errors"
    fi
fi

# Check for large build files (potential issues)
echo -e "${BLUE}Checking for unusually large build files...${NC}"
large_files=$(find ./libs/*/dist -name "*.js" -size +1M 2>/dev/null)
if [ -n "$large_files" ]; then
    warnings+=("Found unusually large build files (>1MB):")
    while IFS= read -r file; do
        size=$(stat -c%s "$file" 2>/dev/null || stat -f%z "$file" 2>/dev/null)
        size_mb=$(echo "scale=2; $size / 1024 / 1024" | bc 2>/dev/null || echo "unknown")
        warnings+=("  - $file (${size_mb}MB)")
    done <<< "$large_files"
fi

# Check for circular dependencies (basic check)
echo -e "${BLUE}Checking for potential circular dependencies...${NC}"
package_json_files=$(find ./libs -name "package.json" -type f)
while IFS= read -r pkg_file; do
    lib_name=$(basename "$(dirname "$pkg_file")")
    if [ -f "$pkg_file" ]; then
        # Check if library depends on itself (basic check)
        self_dep=$(grep -o "@stock-bot/$lib_name" "$pkg_file" 2>/dev/null)
        if [ -n "$self_dep" ]; then
            warnings+=("Potential circular dependency in $lib_name")
        fi
    fi
done <<< "$package_json_files"

# Check for missing package.json files
echo -e "${BLUE}Checking for missing package.json files...${NC}"
lib_dirs=$(find ./libs -maxdepth 1 -type d -name "*" ! -name "libs")
while IFS= read -r lib_dir; do
    if [ -d "$lib_dir" ] && [ ! -f "$lib_dir/package.json" ]; then
        lib_name=$(basename "$lib_dir")
        errors+=("Missing package.json in $lib_name")
    fi
done <<< "$lib_dirs"

# Check for environment variable dependencies
echo -e "${BLUE}Checking for hardcoded paths...${NC}"
hardcoded_paths_win=$(grep -r "g:\\repos\\stock-bot" ./libs 2>/dev/null || true)
hardcoded_paths_unix=$(grep -r "/home/.*/stock-bot" ./libs 2>/dev/null || true)

if [ -n "$hardcoded_paths_win" ]; then
    warnings+=("Found hardcoded Windows paths:")
    while IFS= read -r line; do
        warnings+=("  - $line")
    done <<< "$hardcoded_paths_win"
fi

if [ -n "$hardcoded_paths_unix" ]; then
    warnings+=("Found hardcoded Unix paths:")
    while IFS= read -r line; do
        warnings+=("  - $line")
    done <<< "$hardcoded_paths_unix"
fi

# Summary
echo ""
echo -e "${CYAN}=== Build Verification Summary ===${NC}"

if [ ${#errors[@]} -eq 0 ] && [ ${#warnings[@]} -eq 0 ]; then
    echo -e "${GREEN}✅ Build verification passed - no issues found!${NC}"
    exit 0
fi

if [ ${#errors[@]} -gt 0 ]; then
    echo -e "${RED}❌ Errors found (${#errors[@]}):${NC}"
    for error in "${errors[@]}"; do
        echo -e "${RED}  $error${NC}"
    done
fi

if [ ${#warnings[@]} -gt 0 ]; then
    echo -e "${YELLOW}⚠️  Warnings found (${#warnings[@]}):${NC}"
    for warning in "${warnings[@]}"; do
        echo -e "${YELLOW}  $warning${NC}"
    done
fi

if [ ${#errors[@]} -gt 0 ]; then
    echo ""
    echo -e "${RED}Build verification failed due to errors.${NC}"
    exit 1
else
    echo ""
    echo -e "${YELLOW}Build verification completed with warnings.${NC}"
    exit 0
fi
