GO := $(shell which go)
ifeq (, $(GO))
	$(error "Required Go toolchain (go) not in $(PATH).")
endif

PAGES := $(sort $(wildcard pages/*.html)) pages.yaml
TEMPLATES := $(sort $(wildcard templates/*.gohtml))
ASSETS_DIR := assets
ASSETS_FILES := $(shell find $(ASSETS_DIR) -type f 2>/dev/null)

OUT_DIR := _dist
PAGES_DIR := pages
TEMPLATES_DIR := templates

.PHONY: serve build clean

build: $(OUT_DIR)/index.stamp

$(OUT_DIR)/index.stamp: $(PAGES) $(TEMPLATES) $(ASSETS_FILES) cmd/build/main.go
	@$(GO) run ./cmd/build --pages $(PAGES_DIR) --out $(OUT_DIR) --templates $(TEMPLATES_DIR) --order pages.yaml
	@mkdir -p $(OUT_DIR)
	@if [ -d $(ASSETS_DIR) ]; then rm -rf $(OUT_DIR)/$(ASSETS_DIR); cp -r $(ASSETS_DIR) $(OUT_DIR)/; fi
	@date +%s > $(OUT_DIR)/index.stamp

serve: deps
	@$(GO) run ./cmd/serve --port 8000 $(PWD)

PDF := $(OUT_DIR)/output.pdf
PDF_2UP := $(OUT_DIR)/output-2up.pdf

.PHONY: deps
deps:
	@$(GO) mod tidy

.PHONY: pdf
pdf: build deps
	@echo "Generating PDF by rendering each page and merging..."
	@$(GO) run ./cmd/pdfbook --pages $(OUT_DIR) --order pages.yaml --out $(PDF)

.PHONY: pdf-2up
pdf-2up: build deps
	@echo "Generating 2-up PDF with headless Chrome..."
	@$(GO) run ./cmd/pdf --in $(OUT_DIR)/print_2up.html --out $(PDF_2UP) --w 11 --h 8.5

clean:
	rm -rf $(OUT_DIR) index.html

