SHELL := /usr/bin/env bash

.PHONY: all help build build-frontend build-backend dev test test-race lint check clean docker-build docker-up docker-down

# Default target
all: build

## help: Show this help message
help:
	@echo "RSSPipe Build & Development Commands"
	@echo "====================================="
	@sed -n 's/^##//p' $(MAKEFILE_LIST) | column -t -s ':' | sed -e 's/^/ /'

## build: Build frontend and backend production binary
build: build-frontend build-backend

## build-frontend: Build React PWA frontend bundle (Vite + TypeScript)
build-frontend:
	@echo "==> Building frontend bundle..."
	@cd web && npm install && npm run build
	@echo "✓ Frontend build complete: web/dist"

## build-backend: Build Go backend binary
build-backend:
	@echo "==> Compiling Go binary..."
	@mkdir -p bin
	@CGO_ENABLED=0 go build -ldflags="-s -w" -o bin/rsspipe cmd/server/main.go
	@echo "✓ Backend binary ready: bin/rsspipe"

## dev: Run server locally
dev: build-frontend
	@echo "==> Starting local RSSPipe server..."
	@go run cmd/server/main.go

## test: Run backend Go unit tests
test:
	@echo "==> Running Go unit tests..."
	@go test -v ./...

## check: Run all quality gate checks (formatting, vet, tests, tsc, gitleaks)
check:
	@chmod +x scripts/check.sh
	@./scripts/check.sh

## lint: Run gofmt and go vet
lint:
	@echo "==> Verifying Go formatting..."
	@test -z "$$(gofmt -l internal/ cmd/)" || (echo "Unformatted files:" && gofmt -l internal/ cmd/ && exit 1)
	@echo "==> Running Go vet..."
	@go vet ./...
	@echo "✓ Lint passed."

## format: Format all Go files with gofmt
format:
	@echo "==> Formatting Go files..."
	@gofmt -w internal/ cmd/
	@echo "✓ Formatted."

## docker-build: Build production Docker image
docker-build:
	@echo "==> Building Docker image rsspipe:latest..."
	@docker build -t rsspipe:latest .

## docker-up: Launch RSSPipe with Docker Compose
docker-up:
	@docker compose up -d

## docker-down: Stop Docker Compose services
docker-down:
	@docker compose down

## clean: Remove built binaries and temporary artifacts
clean:
	@echo "==> Cleaning build artifacts..."
	@rm -rf bin/ web/dist/
	@echo "✓ Cleaned."
