# bit Generations: Orbital - Build System
# Uses agbcc (GBA C compiler) for matching decompilation

# Ensure toolchain binaries are on PATH (some envs lack `arm-none-eabi-as` etc.)
export PATH := $(CURDIR)/arm-gnu-toolchain-13.3.rel1-darwin-arm64-arm-none-eabi/bin:$(PATH)

CC = ./agbcc/agbcc
AS = arm-none-eabi-as
LD = arm-none-eabi-ld
OBJCOPY = arm-none-eabi-objcopy

# agbcc flags (typical for GBA games)
CFLAGS = -O2 -mthumb-interwork -Wimplicit -Wparentheses -Wreturn-type

# ROM name
ROM_NAME = orbital
TARGET = $(ROM_NAME).gba
ORIGINAL = "bit Generations - Orbital (Japan) (En).gba"

# Source files
SRC_DIR = src
SOURCES = $(SRC_DIR)/orbital_complete.c

# Build directory
BUILD_DIR = build

.PHONY: all clean compare extract gfx rom verify

# Decomp pipeline (place the ROM in repo root):
#   make extract -> assets/ from ROM
#   make gfx     -> assets/gfx/*.png from assets/
#   make rom     -> build/orbital.gba from code + assets (sha1-verified)
#   make verify  -> code-section stub 100% + full-ROM rebuild check
extract:
	python3 tools/extract_assets.py

gfx: extract
	python3 tools/decode_gfx.py

rom:
	python3 tools/build_rom.py

verify:
	python3 tools/validate_code_section.py
	python3 tools/build_rom.py

all: $(TARGET)

$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

# Compile C to assembly
$(BUILD_DIR)/%.s: $(SRC_DIR)/%.c | $(BUILD_DIR)
	$(CC) $(CFLAGS) -S $< -o $@

# Assemble to object
$(BUILD_DIR)/%.o: $(BUILD_DIR)/%.s
	$(AS) -mcpu=arm7tdmi -o $@ $<

# Link (simplified - just checking compilation)
$(BUILD_DIR)/$(ROM_NAME).elf: $(BUILD_DIR)/orbital_complete.o
	$(LD) -T gba.ld $< -L./agbcc -lgcc -lc -o $@

# Create ROM
$(TARGET): $(BUILD_DIR)/$(ROM_NAME).elf
	$(OBJCOPY) -O binary $< $@

compare: $(TARGET)
	@echo "=== Binary Comparison ==="
	@echo "Original ROM size: $$(wc -c < $(ORIGINAL)) bytes"
	@echo "New ROM size:      $$(wc -c < $(TARGET)) bytes"
	@cmp -l $(ORIGINAL) $(TARGET) | wc -l | xargs -I {} echo "Differences: {} bytes"
	@echo "Accuracy: $$(echo "100 - $(cmp -l $(ORIGINAL) $(TARGET) 2>/dev/null | wc -l) * 100 / $(wc -c < $(ORIGINAL))" | bc)%"

clean:
	rm -rf $(BUILD_DIR) $(TARGET)
