#!/usr/bin/env sh
set -eu
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
REPO_URL="https://github.com/Masterluke77/vendoo.git"
BRANCH="release/1.41.2-git-ignore-boundary-hotfix"
PR_URL="https://github.com/Masterluke77/vendoo/pull/18"
WORK_DIR=$(mktemp -d)
cleanup() { rm -rf "$WORK_DIR"; }
trap cleanup EXIT INT TERM

command -v git >/dev/null 2>&1 || { echo "Git fehlt." >&2; exit 2; }
command -v node >/dev/null 2>&1 || { echo "Node.js wird für den sicheren GitHub-Import benötigt." >&2; exit 2; }

git clone "$REPO_URL" "$WORK_DIR/repo"
cd "$WORK_DIR/repo"
if git ls-remote --exit-code --heads origin "$BRANCH" >/dev/null 2>&1; then
  git fetch origin "$BRANCH"
  git switch --track -c "$BRANCH" "origin/$BRANCH"
else
  git switch -c "$BRANCH"
fi

node "$ROOT_DIR/tools/prepare-git-staging.mjs" "$ROOT_DIR" "$WORK_DIR/repo"

GATE_OUTPUT="$WORK_DIR/git-safety-output.txt"
if ! node tools/verify-git-safety.mjs >"$GATE_OUTPUT" 2>&1; then
  cat "$GATE_OUTPUT" >&2
  mkdir -p "$ROOT_DIR/logs"
  {
    echo "Vendoo Git-Sicherheitsgate – vollständiger Fehlerbericht"
    echo "Projekt: $ROOT_DIR"
    echo
    cat "$GATE_OUTPUT"
  } > "$ROOT_DIR/logs/github-deploy-safety-report.txt"
  echo "Git-Sicherheitsgate fehlgeschlagen. Details: $ROOT_DIR/logs/github-deploy-safety-report.txt" >&2
  exit 1
fi
cat "$GATE_OUTPUT"
rm -f "$ROOT_DIR/logs/github-deploy-safety-report.txt"

git config user.name "Markus Müller"
git config user.email "163446896+Masterluke77@users.noreply.github.com"
git add --all
node tools/verify-source-boundaries-1.41.2.mjs
node tools/verify-git-ignore-boundaries-1.41.2.mjs
ignored_modules="$(git ls-files --others --ignored --exclude-standard -- app/modules || true)"
[ -z "$ignored_modules" ] || { echo "Produktive Moduldateien werden ignoriert: $ignored_modules" >&2; exit 1; }
for required in   app/modules/listings/routes.mjs   app/modules/inventory/index.mjs   app/modules/inventory/repository.mjs   app/modules/inventory/routes.mjs   app/modules/sessions/index.mjs; do
  test -f "$required" || { echo "Pflichtdatei fehlt im Git-Staging: $required" >&2; exit 1; }
  git ls-files --error-unmatch -- "$required" >/dev/null || { echo "Pflichtdatei wird nicht getrackt: $required" >&2; exit 1; }
done
git status --short
printf 'Zum Pushen exakt PUSH eingeben: '
read -r answer
[ "$answer" = "PUSH" ] || { echo "Abgebrochen."; exit 0; }
git commit -m "fix: track native source modules with root-anchored runtime ignores"
git push --set-upstream origin "$BRANCH"
echo "Branch übertragen. Draft Pull Request #15 öffnen: $PR_URL"
