# binary name
BINARY_NAME=mkbrr

# go related variables
GO=go
GOBIN=$(shell $(GO) env GOPATH)/bin
GOLANGCI_LINT ?= $(GO) run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0

# build variables
BUILD_DIR=build
VERSION=$(shell git describe --tags 2>/dev/null || echo "dev")
BUILD_TIME=$(shell date +%FT%T%z)
LDFLAGS=-ldflags "-X main.version=${VERSION} -X main.buildTime=${BUILD_TIME}"

# race detector settings
GORACE=log_path=./race_report.log \
       history_size=2 \
       halt_on_error=1 \
       atexit_sleep_ms=2000

# make all builds and installs
.PHONY: all
all: clean build install

# build binary
.PHONY: build
build:
	@echo "Building ${BINARY_NAME}..."
	@mkdir -p ${BUILD_DIR}
	CGO_ENABLED=0 $(GO) build ${LDFLAGS} -o ${BUILD_DIR}/${BINARY_NAME}

# build with PGO
.PHONY: build-pgo
build-pgo:
	@echo "Building ${BINARY_NAME} with PGO..."
	@if [ ! -f "cpu.pprof" ]; then \
		echo "No PGO profile found. Run 'make profile' first."; \
		exit 1; \
	fi
	@mkdir -p ${BUILD_DIR}
	CGO_ENABLED=0 $(GO) build -pgo=cpu.pprof ${LDFLAGS} -o ${BUILD_DIR}/${BINARY_NAME}

# generate PGO profile with various workloads
.PHONY: profile
profile:
	@echo "Generating PGO profile..."
	@mkdir -p test_data
	@dd if=/dev/urandom of=test_data/test1.bin bs=1M count=100
	@dd if=/dev/urandom of=test_data/test2.bin bs=1M count=100
	@go build -o ${BUILD_DIR}/${BINARY_NAME}
	@echo "Running profile workload 1: Large file..."
	@${BUILD_DIR}/${BINARY_NAME} create test_data/test1.bin --cpuprofile=./cpu1.pprof
	@echo "Running profile workload 2: Multiple files..."
	@${BUILD_DIR}/${BINARY_NAME} create test_data --cpuprofile=./cpu2.pprof
	@echo "Merging profiles..."
	@if [ -f "cpu1.pprof" ] && [ -f "cpu2.pprof" ]; then \
		go tool pprof -proto cpu1.pprof cpu2.pprof > cpu.pprof; \
		rm cpu1.pprof cpu2.pprof; \
		echo "Profile generated at cpu.pprof"; \
	else \
		echo "Error: Profile files not generated correctly"; \
		exit 1; \
	fi
	@rm -rf test_data

# install binary in system path
.PHONY: install
install: build
	@echo "Installing ${BINARY_NAME}..."
	@if [ "$$(id -u)" = "0" ]; then \
		install -m 755 ${BUILD_DIR}/${BINARY_NAME} /usr/local/bin/; \
	else \
		install -m 755 ${BUILD_DIR}/${BINARY_NAME} ${GOBIN}/; \
	fi

# install binary with PGO optimization
.PHONY: install-pgo
install-pgo:
	@echo "Installing ${BINARY_NAME} with PGO..."
	@if [ ! -f "cpu.pprof" ]; then \
		echo "No PGO profile found. Run 'make profile' first."; \
		exit 1; \
	fi
	@mkdir -p ${BUILD_DIR}
	CGO_ENABLED=0 $(GO) build -pgo=cpu.pprof ${LDFLAGS} -o ${BUILD_DIR}/${BINARY_NAME}
	@if [ "$$(id -u)" = "0" ]; then \
		install -m 755 ${BUILD_DIR}/${BINARY_NAME} /usr/local/bin/; \
	else \
		install -m 755 ${BUILD_DIR}/${BINARY_NAME} ${GOBIN}/; \
	fi

# run all tests (excluding large tests)
.PHONY: test
test:
	@echo "Running tests..."
	$(GO) test -v ./...
	@$(MAKE) --no-print-directory test-gui

.PHONY: test-gui
test-gui: gui-dist-placeholder
	@echo "Running GUI tests..."
	cd gui && $(GO) test ./...

# run quick tests with race detector (for CI and quick feedback)
.PHONY: test-race-short
test-race-short:
	@echo "Running quick tests with race detector..."
	GORACE="$(GORACE)" $(GO) test -race -short ./torrent -v
	@if [ -f "./race_report.log" ]; then \
		echo "Race conditions detected! Check race_report.log"; \
		cat "./race_report.log"; \
	fi

# run all tests with race detector (excluding large tests)
.PHONY: test-race
test-race:
	@echo "Running tests with race detector..."
	GORACE="$(GORACE)" $(GO) test -race ./torrent -v
	@if [ -f "./race_report.log" ]; then \
		echo "Race conditions detected! Check race_report.log"; \
		cat "./race_report.log"; \
	fi

# run large tests (resource intensive)
.PHONY: test-large
test-large:
	@echo "Running large tests..."
	GORACE="$(GORACE)" $(GO) test -v -tags=large_tests ./torrent
	@if [ -f "./race_report.log" ]; then \
		echo "Race conditions detected! Check race_report.log"; \
		cat "./race_report.log"; \
	fi

# run tests with coverage
.PHONY: test-coverage
test-coverage:
	@echo "Running tests with coverage..."
	GORACE="$(GORACE)" $(GO) test -v -race -coverprofile=coverage.txt -covermode=atomic ./...
	$(GO) tool cover -html=coverage.txt -o coverage.html
	@if [ -f "./race_report.log" ]; then \
		echo "Race conditions detected! Check race_report.log"; \
		cat "./race_report.log"; \
	fi

# run golangci-lint on the CLI module and the GUI module, at the CI version.
.PHONY: lint lint-cli lint-gui
lint: lint-cli lint-gui

lint-cli:
	$(GOLANGCI_LINT) run

lint-gui: gui-dist-placeholder
	cd gui && $(GOLANGCI_LINT) run

PRECOMMIT_BASE ?= origin/develop

.PHONY: precommit precommit-fmt precommit-lint-cli precommit-lint-gui
precommit: precommit-fmt
	@$(MAKE) --no-print-directory -k precommit-lint-cli precommit-lint-gui
	@echo "Pre-commit checks passed."

precommit-fmt:
	@base=$$(git merge-base $(PRECOMMIT_BASE) HEAD) || exit 1; \
	files=$$({ git diff --name-only --diff-filter=d $$base; git ls-files --others --exclude-standard; } | grep '\.go$$' | sort -u); \
	if [ -n "$$files" ]; then echo "Formatting:" $$files; $(GOLANGCI_LINT) fmt $$files; fi

precommit-lint-cli:
	$(GOLANGCI_LINT) run --new-from-merge-base=$(PRECOMMIT_BASE)

precommit-lint-gui: gui-dist-placeholder
	cd gui && $(GOLANGCI_LINT) run --new-from-merge-base=$(PRECOMMIT_BASE)

# clean build artifacts
.PHONY: clean
clean:
	@echo "Cleaning..."
	@rm -rf ${BUILD_DIR}
	@rm -f coverage.txt coverage.html

# GUI targets
WAILS=$(GOBIN)/wails
WAILS_VERSION=$(shell cd gui && $(GO) list -m -f '{{.Version}}' github.com/wailsapp/wails/v2)
WAILS_TAGS=$(shell [ "$$(uname -s)" = Linux ] && ! pkg-config --exists webkit2gtk-4.0 2>/dev/null && pkg-config --exists webkit2gtk-4.1 2>/dev/null && echo "-tags webkit2_41")

# install wails cli
.PHONY: install-wails
install-wails:
	@echo "Installing Wails CLI..."
	$(GO) install github.com/wailsapp/wails/v2/cmd/wails@$(WAILS_VERSION)

.PHONY: check-wails
check-wails:
	@installed="$$($(WAILS) version 2>/dev/null | grep -m1 -oE '^v[0-9][^[:space:]]*')"; \
	if [ "$$installed" != "$(WAILS_VERSION)" ]; then \
		echo "Wails CLI $${installed:-not found at $(WAILS)}, but gui/go.mod uses $(WAILS_VERSION). Run 'make install-wails'." >&2; \
		exit 1; \
	fi

.PHONY: gui-dist-placeholder
gui-dist-placeholder:
	@mkdir -p gui/frontend/dist
	@[ -n "$$(ls -A gui/frontend/dist)" ] || touch gui/frontend/dist/.gitkeep

.PHONY: gui-bindings
gui-bindings: check-wails gui-dist-placeholder
	@echo "Generating GUI bindings..."
	cd gui && $(WAILS) generate module
	chmod 644 gui/frontend/wailsjs/runtime/*

# run gui in development mode
.PHONY: gui-dev
gui-dev: check-wails
	@echo "Starting GUI in development mode..."
	cd gui && $(WAILS) dev $(WAILS_TAGS)

# build gui for current platform
.PHONY: gui-build
gui-build: check-wails
	@echo "Building GUI..."
	cd gui && $(WAILS) build $(WAILS_TAGS)

# build gui for all platforms
.PHONY: gui-build-all
gui-build-all: check-wails
	@echo "Building GUI for all platforms..."
	cd gui && $(WAILS) build -platform darwin/universal,linux/amd64,windows/amd64 $(WAILS_TAGS)

# clean gui build artifacts
.PHONY: gui-clean
gui-clean:
	@echo "Cleaning GUI build artifacts..."
	@rm -rf gui/build/bin

# show help
.PHONY: help
help:
	@echo "Available targets:"
	@echo "  all            - Clean, build, and install the binary"
	@echo "  build          - Build the binary"
	@echo "  build-pgo      - Build the binary with PGO optimization"
	@echo "  install        - Install the binary in GOPATH"
	@echo "  install-pgo    - Install the binary with PGO optimization"
	@echo "  test           - Run tests, GUI tests included (excluding large tests)"
	@echo "  test-gui       - Run the GUI module tests"
	@echo "  test-race-short- Run quick tests with race detector"
	@echo "  test-race      - Run all tests with race detector (excluding large tests)"
	@echo "  test-large     - Run large tests (resource intensive)"
	@echo "  test-coverage  - Run tests with coverage report"
	@echo "  lint           - Run golangci-lint on the CLI and GUI modules"
	@echo "  precommit      - Format the changed Go files, then lint only the changes since $(PRECOMMIT_BASE)"
	@echo "  clean          - Remove build artifacts"
	@echo "  help           - Show this help"
	@echo ""
	@echo "GUI targets:"
	@echo "  install-wails  - Install the Wails CLI version from gui/go.mod"
	@echo "  check-wails    - Check that the installed Wails CLI matches gui/go.mod"
	@echo "  gui-bindings   - Regenerate the frontend bindings in gui/frontend/wailsjs"
	@echo "  gui-dev        - Run GUI in development mode"
	@echo "  gui-build      - Build GUI for current platform"
	@echo "  gui-build-all  - Build GUI for all platforms"
	@echo "  gui-clean      - Clean GUI build artifacts"
