SHELL := bash
.ONESHELL:
.SHELLFLAGS := -eu -o pipefail -c
.DELETE_ON_ERROR:
MAKEFLAGS += --warn-undefined-variables
MAKEFLAGS += --no-builtin-rules

NODE       ?= node
MAGICK     ?= magick
RSVG       ?= rsvg-convert
XMLLINT    ?= xmllint

IMAGE      ?= scripts/media/kids-story.jpg
IMAGE_SIZE ?= 1400x391

BUILD_DIR  ?= build
PREVIEW_DIR := $(BUILD_DIR)/preview

SVGS := $(wildcard assets/*.svg assets/**/*.svg)

WIDTH  := $(firstword $(subst x, ,$(IMAGE_SIZE)))
HEIGHT := $(lastword $(subst x, ,$(IMAGE_SIZE)))

.DEFAULT_GOAL := help

.PHONY: help all generate check lint image preview clean

help:
	@echo "Usage: make [target]"
	@echo ""
	@echo "Targets:"
	@sed -n 's/^##//p' $(MAKEFILE_LIST) | column -t -s ':' | sed -e 's/^/ /'

all: generate

generate:
	@echo "==> Generating assets and README..."
	$(NODE) scripts/generate.mjs

check: lint

lint:
	@echo "==> Linting scripts and schema..."
	$(NODE) --check scripts/generate.mjs
	$(NODE) -e 'JSON.parse(require("fs").readFileSync("profile.json", "utf8"))'
	@if command -v $(XMLLINT) >/dev/null 2>&1; then \
		if [ -n "$(strip $(SVGS))" ]; then \
			$(XMLLINT) --noout $(SVGS) && echo "svg ok: $(words $(SVGS)) files"; \
		else \
			echo "No SVG files found to lint."; \
		fi \
	else \
		echo "xmllint not found; skipping SVG syntax verification."; \
	fi

image:
	@test -n "$(SRC)" || (echo "Error: SRC is required. Usage: make image SRC=path/to/file.jpg" >&2; exit 1)
	@test -f "$(SRC)" || (echo "Error: File '$(SRC)' does not exist." >&2; exit 1)
	@mkdir -p "$(dir $(IMAGE))"
	@echo "==> Processing image: $(SRC) -> $(IMAGE) ($(IMAGE_SIZE))"
	$(MAGICK) "$(SRC)" \
		-resize "$(WIDTH)x" \
		-gravity center \
		-crop "$(IMAGE_SIZE)+0+0" \
		+repage \
		-strip \
		-sampling-factor 4:2:0 \
		-quality 80 \
		-interlace JPEG \
		"$(IMAGE)"

preview:
	@command -v $(RSVG) >/dev/null 2>&1 || (echo "Error: $(RSVG) is required but not installed." >&2; exit 1)
	@mkdir -p "$(PREVIEW_DIR)"
	@if [ -z "$(strip $(SVGS))" ]; then \
		echo "No SVGS found in assets/"; \
		exit 0; \
	fi
	@echo "==> Rendering $(words $(SVGS)) SVG previews into $(PREVIEW_DIR)..."
	@for f in $(SVGS); do \
		base_name="$${f#assets/}"; \
		out="$(PREVIEW_DIR)/$${base_name//\//-}"; \
		$(RSVG) -z 1.5 "$$f" -o "$${out%.svg}.png"; \
	done
	@echo "Done. Previews available at $(PREVIEW_DIR)/"

clean:
	@echo "==> Cleaning build artifacts..."
	rm -rf "$(BUILD_DIR)"
