.PHONY: all build build-linux build-windows clean test run

# Binary names
BINARY_NAME=corrosion-companion
BINARY_LINUX=$(BINARY_NAME)-linux-amd64
BINARY_WINDOWS=$(BINARY_NAME)-windows-amd64.exe

# Build directory
BUILD_DIR=bin

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

# Version (overridable via: make build-linux VERSION=v1.2.3)
VERSION ?= dev

# Build flags
LDFLAGS = -ldflags "-s -w -X main.version=$(VERSION)"

all: clean build

build: build-linux build-windows

build-linux:
	@echo "Building for Linux (amd64)..."
	@mkdir -p $(BUILD_DIR)
	GOOS=linux GOARCH=amd64 $(GOBUILD) $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_LINUX) ./cmd/agent
	@echo "Built: $(BUILD_DIR)/$(BINARY_LINUX)"

build-windows:
	@echo "Building for Windows (amd64)..."
	@mkdir -p $(BUILD_DIR)
	GOOS=windows GOARCH=amd64 $(GOBUILD) $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_WINDOWS) ./cmd/agent
	@echo "Built: $(BUILD_DIR)/$(BINARY_WINDOWS)"

build-local:
	@echo "Building for current platform..."
	@mkdir -p $(BUILD_DIR)
	$(GOBUILD) $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME) ./cmd/agent
	@echo "Built: $(BUILD_DIR)/$(BINARY_NAME)"

clean:
	@echo "Cleaning..."
	@$(GOCLEAN)
	@rm -rf $(BUILD_DIR)

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

deps:
	@echo "Downloading dependencies..."
	@$(GOMOD) download
	@$(GOMOD) tidy

run: build-local
	@echo "Running agent..."
	@./$(BUILD_DIR)/$(BINARY_NAME)

# Install systemd service (Linux only)
install-service:
	@echo "Installing systemd service..."
	@sudo cp $(BUILD_DIR)/$(BINARY_LINUX) /usr/local/bin/$(BINARY_NAME)
	@sudo cp deployment/corrosion-companion.service /etc/systemd/system/
	@sudo systemctl daemon-reload
	@sudo systemctl enable corrosion-companion
	@echo "Service installed. Configure /etc/corrosion-companion/.env then start with: sudo systemctl start corrosion-companion"

# Development helpers
dev: build-local
	@./$(BUILD_DIR)/$(BINARY_NAME)

fmt:
	@echo "Formatting code..."
	@$(GOCMD) fmt ./...

lint:
	@echo "Running linter..."
	@golangci-lint run ./...

# Show build info
info:
	@echo "Build Information:"
	@echo "  Binary Name: $(BINARY_NAME)"
	@echo "  Linux Binary: $(BUILD_DIR)/$(BINARY_LINUX)"
	@echo "  Windows Binary: $(BUILD_DIR)/$(BINARY_WINDOWS)"
	@echo "  Go Version: $(shell go version)"
