#!/bin/bash

force=0
push=0

API_VERSION=$(sed -n 's/^version *= *"\([^"]*\)".*/\1/p' "$(pwd)"/api/Cargo.toml)
UI_VERSION=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' "$(pwd)"/ui/package.json)

# Parse arguments to detect the force (-f/--force) and push (-p/--push) flags
for arg in "$@"; do
  case $arg in
    -f|--force)
      force=1
      shift
      ;;
    -p|--push)
      push=1
      shift
      ;;
  esac
done

changed_files=$(git diff --name-only "$(git rev-parse HEAD^)")

# Processing UI changes
if echo "$changed_files" | grep -q "^ui/"; then
  ui_tag="ui-${UI_VERSION}"
  if git rev-parse "$ui_tag" >/dev/null 2>&1; then
    if [ $force -eq 1 ]; then
      echo "Force updating tag ${ui_tag} for UI to commit $(git rev-parse HEAD)"
      git tag -fa "${ui_tag}" -m "UI changes in commit $(git rev-parse HEAD)"
      if [ $push -eq 1 ]; then
        echo "Force pushing tag ${ui_tag} to remote"
        git push -f origin "${ui_tag}"
      fi
    else
      echo "Tag ${ui_tag} already exists, skipping UI tagging"
    fi
  else
    echo "Tagging UI with ${ui_tag}"
    git tag -a "${ui_tag}" -m "UI changes in commit $(git rev-parse HEAD)"
    if [ $push -eq 1 ]; then
      echo "Pushing tag ${ui_tag} to remote"
      git push origin "${ui_tag}"
    fi
  fi
fi

# Processing API changes
if echo "$changed_files" | grep -q "^api/"; then
  api_tag="api-${API_VERSION}"
  if git rev-parse "$api_tag" >/dev/null 2>&1; then
    if [ $force -eq 1 ]; then
      echo "Force updating tag ${api_tag} for API to commit $(git rev-parse HEAD)"
      git tag -fa "${api_tag}" -m "API changes in commit $(git rev-parse HEAD)"
      if [ $push -eq 1 ]; then
        echo "Force pushing tag ${api_tag} to remote"
        git push -f origin "${api_tag}"
      fi
    else
      echo "Tag ${api_tag} already exists, skipping API tagging"
    fi
  else
    echo "Tagging API with ${api_tag}"
    git tag -a "${api_tag}" -m "API changes in commit $(git rev-parse HEAD)"
    if [ $push -eq 1 ]; then
      echo "Pushing tag ${api_tag} to remote"
      git push origin "${api_tag}"
    fi
  fi
fi
