#!make
include .dockerenv.dist
-include .dockerenv

### Variable ###

# Composer
COMPOSER=$(PHP_AS_USER) composer

# Detect OS
UNAME_S:=$(shell uname -s)

# OS Specific
ifeq ($(UNAME_S),Darwin)
	SED=sed -i ''
	CUID=1000
	CGID=1000
else
	SED=sed -i
	CUID=$(shell id -u)
	CGID=$(shell id -g)
endif

# Docker
D=docker
DC=$(subst $\",,$(DOCKER_COMPOSE)) --env-file .dockerenv -p $(PROJECT_NAME) -f $(DC_DEV_FILEPATH) -f $(DC_DEV_OVERRIDE_FILEPATH)
DCE=$(DC) exec
DCB=DOCKER_BUILDKIT=1 $(DC) build
DCU=DOCKER_BUILDKIT=1 $(DC) up -d --wait
DCUB=DOCKER_BUILDKIT=1 $(DC) up --build -d --wait
DCD=$(DC) down
DC_DEV_FILEPATH=./hosting/docker-compose.dev.yaml
DC_DEV_OVERRIDE_FILEPATH=./hosting/docker-compose.dev.override.yaml
USER=www-data

# Execute commands as root
PHP_AS_ROOT=$(DCE) -it $(PHP_CONTAINER)

# Execute commands as user
PHP_AS_USER=$(DCE) -u $(USER) $(PHP_CONTAINER)

# Project name
PROJECT_NAME=$(shell basename $(CURDIR))

# Docker containers name
PHP_CONTAINER=api-client-php

# Linux
BASH = bash

# Symfony
PHP_BIN_CONSOLE=$(PHP_AS_USER) php bin/console


### Commands ###
# Equals to docker compose build
build:
	$(DCB)

claude:
	claude "Use ./AGENTS.md as framework"

codex:
	codex "Use ./AGENTS.md as framework"

# Push the current branch (or branch=<name>) and open a GitLab MR against target (default develop).
# Branch convention: <type>/<TICKET>-<slug>, e.g. feature/VWM-1111-something-cool
#   => MR title: [<type>] <TICKET> <Slug words>
# Requires GITLAB_TOKEN (a GitLab personal/project access token with the "api" scope), set in .dockerenv or exported.
# Usage: make create-mr [branch=feature/VWM-1111-something] [target=develop]
create-mr:
	@[ -n "$(GITLAB_TOKEN)" ] || { echo "GITLAB_TOKEN is required. Set GITLAB_TOKEN=glpat-xxx in .dockerenv, or export it: export GITLAB_TOKEN=glpat-xxx"; exit 1; }
	@branch="$(branch)"; \
	target="$(target)"; \
	[ -n "$$branch" ] || branch=$$(git rev-parse --abbrev-ref HEAD); \
	[ -n "$$target" ] || target="develop"; \
	if [ "$$branch" = "HEAD" ] || [ "$$branch" = "$$target" ]; then \
		echo "Cannot create a MR from '$$branch'. Checkout a feature/hotfix/... branch first."; exit 1; \
	fi; \
	type=$$(echo "$$branch" | cut -d/ -f1); \
	rest=$$(echo "$$branch" | cut -d/ -f2-); \
	ticket=$$(echo "$$rest" | grep -oE '^[A-Za-z]+-[0-9]+' || true); \
	if [ -n "$$ticket" ]; then \
		slug=$$(echo "$$rest" | sed "s/^$$ticket-//"); \
	else \
		slug="$$rest"; \
	fi; \
	description=$$(echo "$$slug" | tr '-' ' ' | awk '{print toupper(substr($$0,1,1)) substr($$0,2)}'); \
	ticket_upper=$$(echo "$$ticket" | tr '[:lower:]' '[:upper:]'); \
	if [ -n "$$ticket" ]; then \
		title="[$$type] $$ticket_upper $$description"; \
	else \
		title="[$$type] $$description"; \
	fi; \
	echo "Pushing $$branch..."; \
	git push -u origin "$$branch"; \
	remote_url=$$(git remote get-url origin); \
	host=$$(echo "$$remote_url" | sed -E 's#^(ssh://git@|git@|https://)([^:/]+).*#\2#'); \
	project_path=$$(echo "$$remote_url" | sed -E 's#^.*[:/]([^/]+/[^/]+)\.git$$#\1#'); \
	encoded_path=$$(echo "$$project_path" | sed 's#/#%2F#g'); \
	echo "Creating MR: $$title ($$branch -> $$target)"; \
	response=$$(curl -s -w '\n%{http_code}' --request POST \
		--header "PRIVATE-TOKEN: $(GITLAB_TOKEN)" \
		--data-urlencode "source_branch=$$branch" \
		--data-urlencode "target_branch=$$target" \
		--data-urlencode "title=$$title" \
		"https://$$host/api/v4/projects/$$encoded_path/merge_requests"); \
	http_code=$$(echo "$$response" | tail -n1); \
	body=$$(echo "$$response" | sed '$$d'); \
	if [ "$$http_code" = "201" ]; then \
		web_url=$$(echo "$$body" | grep -oE '"web_url":"[^"]+"' | head -1 | cut -d'"' -f4); \
		echo "MR created: $$web_url"; \
	else \
		echo "Failed to create MR (HTTP $$http_code):"; \
		echo "$$body"; \
		exit 1; \
	fi

# Fix code style
cs-fix:
	$(PHP_AS_USER) php vendor/bin/php-cs-fixer fix --allow-risky=yes
	$(PHP_AS_USER) php vendor/bin/phpstan analyse -c phpstan.neon lib/ --xdebug
	$(PHP_AS_USER) php vendor/bin/psalm --no-cache --show-info=true

# Display the current directory name in snakgfdgdfghe case
current-dirname-snake:
	echo "$(shell basename $(CURDIR) | sed -r 's/([a-z0-9])([A-Z])/\1_\L\2/g' | sed -r 's/-/_/g')"

# Equals to docker compose down
down:
	$(DCD)

# Configure project
configure:
	if [ ! -f .dockerenv ]; \
	then \
		cp .dockerenv.dist .dockerenv; \
		$(SED) "s/\?=/=/" ".dockerenv"; \
		$(SED) "s/UID=.*/UID=$(CUID)/" ".dockerenv"; \
		$(SED) "s/GID=.*/GID=$(CGID)/" ".dockerenv"; \
	fi
	$(shell test -f $(DC_DEV_OVERRIDE_FILEPATH) || touch $(DC_DEV_OVERRIDE_FILEPATH))

run-sonar-qube:
	$(D) run --pull always --rm \
        --volume "$(shell pwd):/usr/src" \
        sonarsource/sonar-scanner-cli

run-test:
	$(PHP_AS_USER) composer run phpunit-coverage
	$(PHP_AS_USER) sed -i 's/\/var\/www\///' phpunit-coverage.xml phpunit-result.xml

# Start project
start:
	$(DCUB)

	#Install dependencies
	$(COMPOSER) install --prefer-dist

	@echo Done.

# Equals to docker compose up -d
up:
	$(DCU)

### Containers access ###

# To go in containers as root
php-root:
	$(PHP_AS_ROOT) bash

# To go in containers as user
php:
	$(PHP_AS_USER) bash

make == make start
.DEFAULT_GOAL := start

# Git

# Internal: update develop, then create and checkout <prefix>/<ticket>-<description> from it.
# ticket and description are each optional, but at least one must be set; the '-' between them is only added when both are present.
# Not meant to be called directly, use create-feature, create-bugfix or create-hotfix.
git-branch-create:
	@[ -n "$(ticket)$(description)" ] || { echo "ticket or description is required."; exit 1; }
	@ticket_slug=$$(echo "$(ticket)" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$$//'); \
	description_slug=$$(echo "$(description)" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/^-//;s/-$$//'); \
	if [ -n "$$ticket_slug" ] && [ -n "$$description_slug" ]; then \
		branch="$(prefix)/$${ticket_slug}-$${description_slug}"; \
	else \
		branch="$(prefix)/$${ticket_slug}$${description_slug}"; \
	fi; \
	echo "Checking out develop and pulling latest..."; \
	git checkout develop; \
	git pull origin develop; \
	echo "Creating branch $$branch..."; \
	git checkout -b "$$branch"

# Usage: make create-bugfix ticket=VWM-1111 description=fix login bug
create-bugfix:
	$(MAKE) git-branch-create prefix=bugfix ticket="$(ticket)" description="$(description)"

git-delete-feature:
	git branch -D $(shell git branch | grep feature/*)

git-delete-hotfix:
	git branch -D $(shell git branch | grep hotfix/*)

# Usage: make create-feature ticket=VWM-1111 description=fix login bug
create-feature:
	$(MAKE) git-branch-create prefix=feature ticket="$(ticket)" description="$(description)"

# Usage: make create-hotfix ticket=VWM-1111 description=fix login bug
create-hotfix:
	$(MAKE) git-branch-create prefix=hotfix ticket="$(ticket)" description="$(description)"

jane-generate: configure
	$(PHP_AS_USER) php bin/merge_docs.php
	$(PHP_AS_USER) php bin/jane_generate.php generate --config-file=config/all.php
	rm -rf ./gen # bug jane create a gen empty directory after generate
	$(PHP_AS_USER) composer run quality
	@echo Jane files have been generated !

update:
	COMMIT=$$(git rev-parse HEAD); \
	git pull; \
	if [ "$$COMMIT" != $$(git rev-parse HEAD) ]; \
	then \
		$(MAKE); \
	fi

# Fix code style, check code quality
pre-push:
	rm -rf ./.cache/*
	$(PHP_AS_USER) composer run quality
	$(PHP_AS_USER) composer run phpunit-coverage
	$(PHP_AS_USER) sed -i 's/\/var\/www\///' phpunit-coverage.xml phpunit-result.xml
	$(MAKE) run-sonar-qube

# DEV Only
deploy-iam:
	cp -r ./lib/* ../iam/vendor/noahvet/reef-api-client/lib/

deploy-bsm:
	cp -r ./lib/* ../bsm/vendor/noahvet/reef-api-client/lib/

deploy-portal:
	cp -r ./lib/* ../portal/vendor/noahvet/reef-api-client/lib/

update-dev-images:
	docker build -t gitlab.vetinweb.com:5050/reef/api-client/php:dev --pull --target dev --network=host -f hosting/php/Dockerfile .

hard-reset:
	rm -rf vendor config/all.json .dockerenv
