.PHONY: setup lint clean help

TIGER_VERSION := 1.15.0
TIGER_BIN     := tools/ck3-tiger
ENV_FILE      := .env
LOCAL_MOD     := .lords-of-ash-local.mod

-include $(ENV_FILE)

# Detect platform for binary download
UNAME_S := $(shell uname -s)
UNAME_M := $(shell uname -m)
ifeq ($(UNAME_S),Linux)
    TIGER_ARCHIVE := ck3-tiger-linux-v$(TIGER_VERSION).tar.gz
else ifeq ($(UNAME_S),Darwin)
    TIGER_ARCHIVE :=
else ifneq (,$(findstring MINGW,$(UNAME_S)))
    TIGER_ARCHIVE := ck3-tiger-windows-v$(TIGER_VERSION).zip
else ifneq (,$(findstring MSYS,$(UNAME_S)))
    TIGER_ARCHIVE := ck3-tiger-windows-v$(TIGER_VERSION).zip
else
    TIGER_ARCHIVE :=
endif

TIGER_URL := https://github.com/amtep/tiger/releases/download/v$(TIGER_VERSION)/$(TIGER_ARCHIVE)

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

setup: ## Configure ck3-tiger (usage: make setup CK3_GAME_DIR=/path/to/ck3)
ifndef CK3_GAME_DIR
	$(error CK3_GAME_DIR is required. Usage: make setup CK3_GAME_DIR=/path/to/ck3)
endif
	@test -d "$(CK3_GAME_DIR)/game" || (echo "Error: $(CK3_GAME_DIR)/game not found. Is this the CK3 install directory?" && exit 1)
	@echo 'CK3_GAME_DIR=$(CK3_GAME_DIR)' > $(ENV_FILE)
	@sed 's|path="mod/lords_of_ash"|path="lords_of_ash"|' lords-of-ash.mod > $(LOCAL_MOD)
ifeq ($(TIGER_ARCHIVE),)
	@echo "Warning: no pre-built ck3-tiger binary for $(UNAME_S)/$(UNAME_M)."
	@echo "Install manually: cargo install ck3-tiger"
else
	@if [ ! -x $(TIGER_BIN) ]; then \
		echo "Downloading ck3-tiger v$(TIGER_VERSION) for $(UNAME_S)..."; \
		mkdir -p tools; \
		curl -fsSL "$(TIGER_URL)" -o "tools/$(TIGER_ARCHIVE)"; \
		case "$(TIGER_ARCHIVE)" in \
			*.tar.gz) tar -xzf "tools/$(TIGER_ARCHIVE)" -C tools;; \
			*.zip)    unzip -qo "tools/$(TIGER_ARCHIVE)" -d tools;; \
		esac; \
		mv tools/ck3-tiger-*/ck3-tiger $(TIGER_BIN); \
		rm -rf tools/ck3-tiger-*/ "tools/$(TIGER_ARCHIVE)"; \
		echo "Installed $(TIGER_BIN)"; \
	else \
		echo "ck3-tiger already installed."; \
	fi
endif
	@echo "Setup complete. Run 'make lint' to validate the mod."

lint: ## Run ck3-tiger against the mod
	@test -f $(ENV_FILE) || (echo "Run 'make setup CK3_GAME_DIR=/path/to/ck3' first." && exit 1)
	@test -f $(LOCAL_MOD) || (echo "Run 'make setup CK3_GAME_DIR=/path/to/ck3' first." && exit 1)
	@if [ -x $(TIGER_BIN) ]; then \
		$(TIGER_BIN) --game "$(CK3_GAME_DIR)" $(LOCAL_MOD); \
	elif command -v ck3-tiger >/dev/null 2>&1; then \
		ck3-tiger --game "$(CK3_GAME_DIR)" $(LOCAL_MOD); \
	else \
		echo "ck3-tiger not found. Run 'make setup' or install via 'cargo install ck3-tiger'."; \
		exit 1; \
	fi

clean: ## Remove generated local files and tools
	rm -rf tools $(ENV_FILE) $(LOCAL_MOD)
