#!/bin/bash
# EN: Debug build errors with verbose output
# VI: Debug lỗi build với output chi tiết

set -e

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

if [ $# -eq 0 ]; then
    echo -e "${RED}Error: Service name required${NC}"
    echo "Usage: $0 <service-name>"
    echo "Example: $0 my-service-net"
    exit 1
fi

SERVICE_NAME=$1
SERVICE_DIR="services/${SERVICE_NAME}"
LOG_FILE="build-debug-$(date +%Y%m%d-%H%M%S).log"

echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}  Debug Build: ${SERVICE_NAME}${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# Check if service exists
if [ ! -d "$SERVICE_DIR" ]; then
    echo -e "${RED}✗ Service not found: $SERVICE_DIR${NC}"
    exit 1
fi

cd "$SERVICE_DIR"

# Find solution file
SOLUTION_FILE=$(find . -maxdepth 1 -name "*.slnx" -o -name "*.sln" | head -n 1)

if [ -z "$SOLUTION_FILE" ]; then
    echo -e "${RED}✗ No solution file found${NC}"
    exit 1
fi

echo -e "${YELLOW}Step 1: Cleaning previous build artifacts...${NC}"
dotnet clean "$SOLUTION_FILE"

echo ""
echo -e "${YELLOW}Step 2: Restoring packages with detailed output...${NC}"
dotnet restore "$SOLUTION_FILE" -v detailed 2>&1 | tee "$LOG_FILE"

echo ""
echo -e "${YELLOW}Step 3: Building with detailed verbosity...${NC}"
echo -e "${YELLOW}(This will take longer but show all information)${NC}"
echo ""

# Build with detailed output
dotnet build "$SOLUTION_FILE" --no-restore -v detailed 2>&1 | tee -a "$LOG_FILE"

BUILD_STATUS=$?

echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if [ $BUILD_STATUS -eq 0 ]; then
    echo -e "${GREEN}✓ Build completed successfully!${NC}"
    echo ""
    echo "Log saved to: $LOG_FILE"
else
    echo -e "${RED}✗ Build failed${NC}"
    echo ""
    echo "Full debug log saved to: $LOG_FILE"
    echo ""
    echo -e "${YELLOW}Common issues to check:${NC}"
    echo "  1. Missing package references (dotnet add package)"
    echo "  2. Using statements (add 'using' directive)"
    echo "  3. NuGet package version conflicts"
    echo "  4. Target framework mismatch"
    echo ""
    echo "Grep for errors:"
    echo "  cat $LOG_FILE | grep -i error"
    echo "  cat $LOG_FILE | grep -i CS[0-9]"
    exit 1
fi
