#!/usr/bin/env bash
set -euo pipefail

SHADE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BASHRC="$HOME/.bashrc"
REGISTRY="https://gt.zyon.no"
GITEA_USER="Stian"

PACKAGES=(
  core
  proto
  crypto-web
  observability
  keychain
  key-transparency
  storage-sqlite
  storage-postgres
  storage-indexeddb
  storage-encrypted
  streams
  transport
  transport-bridge
  transport-webrtc
  server
  inbox-server
  inbox
  transfer
  files
  recovery
  observer
  dashboard
  sdk
  widgets
  cli
)

echo "Shade publish-script — kjører fra $SHADE_DIR"
echo

FORCE_NEW_TOKEN=0
if [ "${1:-}" = "--new-token" ]; then
  FORCE_NEW_TOKEN=1
fi

if [ -n "${GITEA_TOKEN:-}" ] && [ $FORCE_NEW_TOKEN -eq 0 ]; then
  TOKEN="$GITEA_TOKEN"
  echo "Bruker lagret GITEA_TOKEN (starter med ${TOKEN:0:8}…)"
  echo "(Kjør med --new-token for å bytte token)"
else
  echo "Lim inn GITEA_TOKEN og trykk Enter:"
  read -r TOKEN
  if [ -z "${TOKEN:-}" ]; then
    echo "Tomt token, avbryter."
    exit 1
  fi
  echo "Token-lengde: ${#TOKEN} tegn"
  echo "Token starter med: ${TOKEN:0:8}…"
fi

echo "Sjekker at tokenet ikke er ugyldig ..."

HTTP_STATUS=$(curl -sS -o /dev/null -w "%{http_code}" \
  -H "Authorization: token $TOKEN" \
  "$REGISTRY/api/v1/user")

if [ "$HTTP_STATUS" = "401" ]; then
  echo "401: tokenet er ugyldig eller utløpt. Lag et nytt i Gitea."
  exit 1
fi
echo "Token akseptert av server (HTTP $HTTP_STATUS)."

FIRST_PKG_JSON="$SHADE_DIR/packages/shade-core/package.json"
if [ ! -f "$FIRST_PKG_JSON" ]; then
  echo "Fant ikke $FIRST_PKG_JSON"
  exit 1
fi

CURRENT_VERSION=$(grep -oP '"version"\s*:\s*"\K[^"]+' "$FIRST_PKG_JSON" | head -1)
echo
echo "Nåværende versjon i package.json: $CURRENT_VERSION"
echo "Sjekker om $CURRENT_VERSION allerede finnes i registry ..."

CONFLICT_FOUND=0
for pkg in "${PACKAGES[@]}"; do
  body=$(curl -sS -H "Authorization: token $TOKEN" \
    "$REGISTRY/api/packages/$GITEA_USER/npm/@shade/$pkg" 2>/dev/null || true)
  if echo "$body" | grep -q "\"$CURRENT_VERSION\":[[:space:]]*{"; then
    CONFLICT_FOUND=1
    echo "  konflikt: @shade/$pkg@$CURRENT_VERSION finnes allerede"
  fi
done

if [ $CONFLICT_FOUND -eq 1 ]; then
  echo
  echo "Versjon $CURRENT_VERSION er allerede publisert."
  echo "Skriv inn ny versjon (f.eks. 0.1.1) og trykk Enter:"
  read -r NEW_VERSION
  if [ -z "${NEW_VERSION:-}" ]; then
    echo "Tom versjon, avbryter."
    exit 1
  fi
  if [ "$NEW_VERSION" = "$CURRENT_VERSION" ]; then
    echo "Ny versjon er lik nåværende, avbryter."
    exit 1
  fi
  echo "Oppdaterer alle pakker til $NEW_VERSION ..."
  for pkg in "${PACKAGES[@]}"; do
    pkg_dir="$SHADE_DIR/packages/shade-$pkg"
    if [ -f "$pkg_dir/package.json" ]; then
      (cd "$pkg_dir" && npm pkg set version="$NEW_VERSION" >/dev/null)
      echo "  shade-$pkg → $NEW_VERSION"
    fi
  done
else
  echo "Ingen konflikter — bruker eksisterende versjon $CURRENT_VERSION."
fi

EXISTING_LINE=$(grep '^export GITEA_TOKEN=' "$BASHRC" 2>/dev/null || true)
if [ "$EXISTING_LINE" != "export GITEA_TOKEN=$TOKEN" ]; then
  if [ -n "$EXISTING_LINE" ]; then
    sed -i '/^export GITEA_TOKEN=/d' "$BASHRC"
  fi
  echo "export GITEA_TOKEN=$TOKEN" >> "$BASHRC"
  echo "Lagret GITEA_TOKEN i $BASHRC"
fi

export GITEA_TOKEN="$TOKEN"

cd "$SHADE_DIR"
echo
echo "Type-check (strict TS) før publish ..."
echo "----------------------------------------"
bun run scripts/typecheck-all.ts
echo
echo "Kjører scripts/publish-all.ts i $SHADE_DIR"
echo "----------------------------------------"
bun run scripts/publish-all.ts
