.PHONY: build run test clean docker-build docker-run help

# Binary name
BINARY_NAME=ide
BINARY_PATH=bin/$(BINARY_NAME)

# Go parameters
GOCMD=go
GOBUILD=$(GOCMD) build
GOTEST=$(GOCMD) test
GOMOD=$(GOCMD) mod
GOCLEAN=$(GOCMD) clean

# Build flags
BUILD_FLAGS=-ldflags="-s -w"
BUILD_DIR=./cmd/ide

help: ## Show this help
	@echo "Available targets:"
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "  %-15s %s\n", $$1, $$2}'

build: ## Build the IDE binary
	@echo "Building $(BINARY_NAME)..."
	@mkdir -p bin
	$(GOBUILD) $(BUILD_FLAGS) -o $(BINARY_PATH) $(BUILD_DIR)
	@echo "✓ Built: $(BINARY_PATH)"

run: build ## Build and run the IDE
	@echo "Starting IDE server..."
	./$(BINARY_PATH) --workspace=.

run-verbose: build ## Build and run with verbose logging
	@echo "Starting IDE server (verbose mode)..."
	./$(BINARY_PATH) --workspace=. -v

test: ## Run all tests
	@echo "Running tests..."
	$(GOTEST) -v ./...

test-coverage: ## Run tests with coverage
	@echo "Running tests with coverage..."
	$(GOTEST) -v -coverprofile=coverage.out ./...
	$(GOCMD) tool cover -html=coverage.out -o coverage.html
	@echo "✓ Coverage report: coverage.html"

test-race: ## Run tests with race detector
	@echo "Running tests with race detector..."
	$(GOTEST) -race -v ./...

deps: ## Download dependencies
	@echo "Downloading dependencies..."
	$(GOMOD) download
	$(GOMOD) tidy
	@echo "✓ Dependencies downloaded"

clean: ## Clean build artifacts
	@echo "Cleaning..."
	$(GOCLEAN)
	rm -rf bin/
	rm -f coverage.out coverage.html
	@echo "✓ Cleaned"

docker-build: ## Build Docker image
	@echo "Building Docker image..."
	docker build -t go-ide:latest .
	@echo "✓ Docker image built: go-ide:latest"

docker-run: ## Run Docker container
	@echo "Running Docker container..."
	docker run -p 3000:3000 -v $(PWD):/workspace go-ide:latest

install-tools: ## Install required tools (gopls, delve)
	@echo "Installing gopls..."
	go install golang.org/x/tools/gopls@latest
	@echo "Installing delve..."
	go install github.com/go-delve/delve/cmd/dlv@latest
	@echo "✓ Tools installed"

fmt: ## Format Go code
	@echo "Formatting code..."
	gofmt -s -w .
	@echo "✓ Code formatted"

lint: ## Run linter (requires golangci-lint)
	@echo "Running linter..."
	golangci-lint run ./...

dev: ## Run in development mode with auto-reload (requires air)
	@echo "Starting development server..."
	air -c .air.toml

.DEFAULT_GOAL := help
