# Directorios
DIR_ROOT       := $(dir $(abspath $(MAKEFILE_LIST)))
DIR_SOURCES    := $(addsuffix /, $(DIR_ROOT)src)
DIR_BIN        := $(addsuffix /, $(DIR_ROOT))
DIR_BUILD      := $(addsuffix /, $(DIR_ROOT)build)

# Variables
TARGET_NAME    := shadertoy
TARGET_FILE    := $(DIR_BIN)$(TARGET_NAME)
APP_NAME       := Shadertoy
RELEASE_FOLDER := shadertoy_release
RESOURCE_FILE  := release/shadertoy.res

# Versión automática basada en la fecha actual (formato YYYY.MM.DD para que
# CFBundleShortVersionString del bundle macOS sea conforme a la spec de Apple).
ifeq ($(OS),Windows_NT)
    VERSION := $(shell powershell -Command "Get-Date -Format 'yyyy.MM.dd'")
else
    VERSION := $(shell date +%Y.%m.%d)
endif

# Variables específicas para Windows (usando APP_NAME)
ifeq ($(OS),Windows_NT)
    WIN_TARGET_FILE    := $(DIR_BIN)$(APP_NAME)
    WIN_RELEASE_FILE   := $(RELEASE_FOLDER)/$(APP_NAME)
else
    WIN_TARGET_FILE    := $(TARGET_FILE)
    WIN_RELEASE_FILE   := $(RELEASE_FOLDER)/$(TARGET_NAME)
endif

# Nombres para los ficheros de lanzamiento
WINDOWS_RELEASE             := $(TARGET_NAME)-$(VERSION)-win32-x64.zip
MACOS_APPLE_SILICON_RELEASE := $(TARGET_NAME)-$(VERSION)-macos-apple-silicon.dmg
LINUX_RELEASE               := $(TARGET_NAME)-$(VERSION)-linux.tar.gz

# Lista completa de archivos fuente
APP_SOURCES := \
    src/main.cpp \
    src/rendering/shader_backend.cpp \
    src/rendering/opengl_shader_backend.cpp \
    src/rendering/sdl3gpu/sdl3gpu_shader_backend.cpp \
    src/audio/jail_audio.cpp \
    third_party/glad/src/glad.c \
    third_party/stb_vorbis_impl.cpp

# Includes
INCLUDES := -Isrc -Ithird_party/glad/include -Ithird_party

# Variables según el sistema operativo
ifeq ($(OS),Windows_NT)
    FixPath         = $(subst /,\\,$1)
    CXXFLAGS        := -std=c++17 -Wall -Os -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -static-libgcc -Wl,-Bstatic -lpthread -Wl,-Bdynamic -Wl,-subsystem,windows -DWINDOWS_BUILD
    CXXFLAGS_DEBUG  := -std=c++17 -Wall -g -D_DEBUG -DWINDOWS_BUILD
    LDFLAGS         := -lmingw32 -lws2_32 -lSDL3 -lopengl32
    RM              := del /Q
    MKDIR           := mkdir
else
    FixPath         = $1
    CXXFLAGS        := -std=c++17 -Wall -Os -ffunction-sections -fdata-sections
    CXXFLAGS_DEBUG  := -std=c++17 -Wall -g -D_DEBUG
    LDFLAGS         := -lSDL3
    RMFILE          := rm -f
    RMDIR           := rm -rdf
    MKDIR           := mkdir -p
    UNAME_S         := $(shell uname -s)
    ifeq ($(UNAME_S),Linux)
        CXXFLAGS    += -DLINUX_BUILD
        LDFLAGS     += -lGL
    endif
    ifeq ($(UNAME_S),Darwin)
        CXXFLAGS       += -Wno-deprecated -DMACOS_BUILD
        CXXFLAGS_DEBUG += -Wno-deprecated -DMACOS_BUILD
        LDFLAGS        += -framework OpenGL
        # Configurar arquitectura (por defecto arm64, como en CMake)
        CXXFLAGS       += -arch arm64
        CXXFLAGS_DEBUG += -arch arm64
    endif
endif

# Reglas para compilación
windows:
	@echo off
	@echo Compilando para Windows con nombre: "$(APP_NAME).exe"
	windres release/shadertoy.rc -O coff -o $(RESOURCE_FILE)
	$(CXX) $(APP_SOURCES) $(RESOURCE_FILE) $(INCLUDES) $(CXXFLAGS) $(LDFLAGS) -o "$(WIN_TARGET_FILE).exe"
	strip -s -R .comment -R .gnu.version "$(WIN_TARGET_FILE).exe" --strip-unneeded

windows_debug:
	@echo off
	@echo Compilando version debug para Windows: "$(APP_NAME)_debug.exe"
	$(CXX) $(APP_SOURCES) $(INCLUDES) -DDEBUG $(CXXFLAGS_DEBUG) $(LDFLAGS) -o "$(WIN_TARGET_FILE)_debug.exe"

windows_release:
	@echo off
	@echo Creando release para Windows - Version: $(VERSION)

# Crea carpeta temporal 'RELEASE_FOLDER'
	powershell if (Test-Path "$(RELEASE_FOLDER)") {Remove-Item "$(RELEASE_FOLDER)" -Recurse -Force}
	powershell if (-not (Test-Path "$(RELEASE_FOLDER)")) {New-Item "$(RELEASE_FOLDER)" -ItemType Directory}

# Copia la carpeta 'shaders'
	powershell Copy-Item -Path "shaders" -Destination "$(RELEASE_FOLDER)" -recurse -Force
	powershell Copy-Item -Path "data" -Destination "$(RELEASE_FOLDER)" -recurse -Force

# Copia los ficheros que están en la raíz del proyecto
	powershell Copy-Item "LICENSE" -Destination "$(RELEASE_FOLDER)"
	powershell Copy-Item "README.md" -Destination "$(RELEASE_FOLDER)"
	powershell Copy-Item "release\*.dll" -Destination "$(RELEASE_FOLDER)"

# Compila el recurso de icono
	@windres release/shadertoy.rc -O coff -o $(RESOURCE_FILE)

# Compila
	$(CXX) $(APP_SOURCES) $(RESOURCE_FILE) $(INCLUDES) -DRELEASE_BUILD $(CXXFLAGS) $(LDFLAGS) -o "$(WIN_RELEASE_FILE).exe"
	strip -s -R .comment -R .gnu.version "$(WIN_RELEASE_FILE).exe" --strip-unneeded

# Crea el fichero .zip
	powershell if (Test-Path "$(WINDOWS_RELEASE)") {Remove-Item "$(WINDOWS_RELEASE)"}
	powershell Compress-Archive -Path "$(RELEASE_FOLDER)"/* -DestinationPath "$(WINDOWS_RELEASE)"
	@echo Release creado: $(WINDOWS_RELEASE)

# Elimina la carpeta temporal 'RELEASE_FOLDER'
	powershell if (Test-Path "$(RELEASE_FOLDER)") {Remove-Item "$(RELEASE_FOLDER)" -Recurse -Force}

macos:
	@echo "Compilando para macOS: $(TARGET_NAME)"
	$(CXX) $(APP_SOURCES) $(INCLUDES) $(CXXFLAGS) $(LDFLAGS) -o "$(TARGET_FILE)"

macos_debug:
	@echo "Compilando version debug para macOS: $(TARGET_NAME)_debug"
	$(CXX) $(APP_SOURCES) $(INCLUDES) -DDEBUG $(CXXFLAGS_DEBUG) $(LDFLAGS) -o "$(TARGET_FILE)_debug"

macos_release:
	@echo "Creando release para macOS - Version: $(VERSION)"

# Verifica dependencias necesarias (create-dmg). Si falta, intenta instalarla
# con brew; si brew tampoco está, indica el comando exacto al usuario.
	@command -v create-dmg >/dev/null 2>&1 || { \
		echo ""; \
		echo "============================================"; \
		echo "  Falta la dependencia: create-dmg"; \
		echo "============================================"; \
		if command -v brew >/dev/null 2>&1; then \
			echo "  Instalando con: brew install create-dmg"; \
			brew install create-dmg || { \
				echo ""; \
				echo "  ERROR: 'brew install create-dmg' ha fallado."; \
				echo "  Ejecuta el comando manualmente y vuelve a probar."; \
				exit 1; \
			}; \
		else \
			echo "  Homebrew no está instalado."; \
			echo "  Instálalo desde https://brew.sh y luego ejecuta:"; \
			echo "      brew install create-dmg"; \
			exit 1; \
		fi; \
	}

# Elimina datos de compilaciones anteriores
	$(RMDIR) "$(RELEASE_FOLDER)"
	$(RMFILE) tmp.dmg
	$(RMFILE) "$(MACOS_APPLE_SILICON_RELEASE)"

# Crea la carpeta temporal para hacer el trabajo y las carpetas obligatorias para crear una app de macos
	$(MKDIR) "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Frameworks"
	$(MKDIR) "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/MacOS"
	$(MKDIR) "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Resources"

# Copia carpetas y ficheros
	cp -R shaders "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Resources"
	cp -R data "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Resources"
	cp -R release/frameworks/SDL3.xcframework "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Frameworks"
	cp release/icon.icns "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Resources"
	cp release/Info.plist "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents"
	cp LICENSE "$(RELEASE_FOLDER)"
	cp README.md "$(RELEASE_FOLDER)"

# Actualiza versión en Info.plist
	@echo "Actualizando Info.plist con versión $(VERSION)..."
	@RAW_VERSION=$$(echo "$(VERSION)" | sed 's/^v//'); \
	sed -i '' '/<key>CFBundleShortVersionString<\/key>/{n;s|<string>.*</string>|<string>'"$$RAW_VERSION"'</string>|;}' "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Info.plist"; \
	sed -i '' '/<key>CFBundleVersion<\/key>/{n;s|<string>.*</string>|<string>'"$$RAW_VERSION"'</string>|;}' "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/Info.plist"

# Compila la versión para procesadores Apple Silicon
	$(CXX) $(APP_SOURCES) $(INCLUDES) -DMACOS_BUNDLE -DRELEASE_BUILD $(CXXFLAGS) $(LDFLAGS) -o "$(RELEASE_FOLDER)/$(APP_NAME).app/Contents/MacOS/$(TARGET_NAME)" -rpath @executable_path/../Frameworks/ -target arm64-apple-macos11

# Firma la aplicación
	codesign --deep --force --sign - --timestamp=none "$(RELEASE_FOLDER)/$(APP_NAME).app"

# Empaqueta el .dmg de la versión Apple Silicon con create-dmg
	@echo "Creando DMG Apple Silicon con iconos de 96x96..."
	create-dmg \
	  --volname "$(APP_NAME)" \
	  --window-pos 200 120 \
	  --window-size 720 300 \
	  --icon-size 96 \
	  --text-size 12 \
	  --icon "$(APP_NAME).app" 278 102 \
	  --icon "LICENSE" 441 102 \
	  --icon "README.md" 604 102 \
	  --app-drop-link 115 102 \
	  --hide-extension "$(APP_NAME).app" \
	  "$(MACOS_APPLE_SILICON_RELEASE)" \
	  "$(RELEASE_FOLDER)" || true
	@echo "Release Apple Silicon creado: $(MACOS_APPLE_SILICON_RELEASE)"

# Elimina las carpetas temporales
	$(RMDIR) "$(RELEASE_FOLDER)"

linux:
	@echo "Compilando para Linux: $(TARGET_NAME)"
	$(CXX) $(APP_SOURCES) $(INCLUDES) $(CXXFLAGS) $(LDFLAGS) -o "$(TARGET_FILE)"
	strip -s -R .comment -R .gnu.version "$(TARGET_FILE)" --strip-unneeded

linux_debug:
	@echo "Compilando version debug para Linux: $(TARGET_NAME)_debug"
	$(CXX) $(APP_SOURCES) $(INCLUDES) -DDEBUG $(CXXFLAGS_DEBUG) $(LDFLAGS) -o "$(TARGET_FILE)_debug"

linux_release:
	@echo "Creando release para Linux - Version: $(VERSION)"
# Elimina carpetas previas
	$(RMDIR) "$(RELEASE_FOLDER)"

# Crea la carpeta temporal para realizar el lanzamiento
	$(MKDIR) "$(RELEASE_FOLDER)"

# Copia ficheros
	cp -R shaders "$(RELEASE_FOLDER)"
	cp -R data "$(RELEASE_FOLDER)"
	cp LICENSE "$(RELEASE_FOLDER)"
	cp README.md "$(RELEASE_FOLDER)"

# Compila
	$(CXX) $(APP_SOURCES) $(INCLUDES) -DRELEASE_BUILD $(CXXFLAGS) $(LDFLAGS) -o "$(RELEASE_FOLDER)/$(TARGET_NAME)"
	strip -s -R .comment -R .gnu.version "$(RELEASE_FOLDER)/$(TARGET_NAME)" --strip-unneeded

# Empaqueta ficheros
	$(RMFILE) "$(LINUX_RELEASE)"
	tar -czvf "$(LINUX_RELEASE)" -C "$(RELEASE_FOLDER)" .
	@echo "Release creado: $(LINUX_RELEASE)"

# Elimina la carpeta temporal
	$(RMDIR) "$(RELEASE_FOLDER)"

# Regla para mostrar la versión actual
show_version:
	@echo "Version actual: $(VERSION)"

# Regla de ayuda
help:
	@echo "Makefile para Shadertoy"
	@echo "Comandos disponibles:"
	@echo "  windows          - Compilar para Windows"
	@echo "  windows_debug    - Compilar debug para Windows"
	@echo "  windows_release  - Crear release completo para Windows"
	@echo "  linux            - Compilar para Linux"
	@echo "  linux_debug      - Compilar debug para Linux"
	@echo "  linux_release    - Crear release completo para Linux"
	@echo "  macos            - Compilar para macOS"
	@echo "  macos_debug      - Compilar debug para macOS"
	@echo "  macos_release    - Crear release completo para macOS"
	@echo "  show_version     - Mostrar version actual ($(VERSION))"
	@echo "  help             - Mostrar esta ayuda"

.PHONY: windows windows_debug windows_release macos macos_debug macos_release linux linux_debug linux_release show_version help

FORCE:
