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

# Publish Vigthoria CLI release artifact + manifest entry.
# Usage:
#   HOST_DOWNLOADS_DIR=/path/to/downloads \
#   HOST_MANIFEST_FILE=/path/to/releases/manifest.json \
#   ./scripts/release/publish-cli-release.sh 1.9.0

VERSION="${1:-}"
if [[ -z "$VERSION" ]]; then
  echo "Usage: $0 <version>"
  exit 1
fi

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
PKG_FILE="$REPO_ROOT/vigthoria-cli-${VERSION}.tgz"
HOST_DOWNLOADS_DIR="${HOST_DOWNLOADS_DIR:-}"
HOST_MANIFEST_FILE="${HOST_MANIFEST_FILE:-}"
PUBLIC_BASE_URL="${PUBLIC_BASE_URL:-https://cli.vigthoria.io/downloads}"
CHANNEL="${CHANNEL:-stable}"

if [[ ! -f "$PKG_FILE" ]]; then
  echo "Artifact not found: $PKG_FILE"
  echo "Run: npm pack"
  exit 1
fi

if [[ -z "$HOST_DOWNLOADS_DIR" || -z "$HOST_MANIFEST_FILE" ]]; then
  echo "Set HOST_DOWNLOADS_DIR and HOST_MANIFEST_FILE before running."
  exit 1
fi

SHA256="$(sha256sum "$PKG_FILE" | awk '{print $1}')"
URL="$PUBLIC_BASE_URL/vigthoria-cli-${VERSION}.tgz"

echo "Publishing vigthoria-cli v${VERSION}"
echo "Artifact: $PKG_FILE"
echo "SHA256:   $SHA256"
echo "URL:      $URL"

install -d "$HOST_DOWNLOADS_DIR"
cp -f "$PKG_FILE" "$HOST_DOWNLOADS_DIR/"

echo "Copied artifact to $HOST_DOWNLOADS_DIR"

if [[ ! -f "$HOST_MANIFEST_FILE" ]]; then
  echo "Manifest does not exist at: $HOST_MANIFEST_FILE"
  echo "Create it first with {\"channels\":{\"stable\":{}}}"
  exit 1
fi

python3 - << PYEOF
import json, pathlib
manifest_path = pathlib.Path(r"$HOST_MANIFEST_FILE")
data = json.loads(manifest_path.read_text())
data.setdefault("channels", {})
data["channels"].setdefault("$CHANNEL", {})
data["channels"]["$CHANNEL"].update({
  "version": "$VERSION",
  "url": "$URL",
  "sha256": "$SHA256",
  "notes": "Automated publish via scripts/release/publish-cli-release.sh"
})
manifest_path.write_text(json.dumps(data, indent=2) + "\n")
print("Manifest updated:", manifest_path)
PYEOF

echo "Publish complete."
echo "Verification commands:"
echo "  curl -I $URL"
echo "  curl -fsSL https://coder.vigthoria.io/releases/manifest.json | head -40"
echo "  node dist/index.js update --check --manifest https://coder.vigthoria.io/releases/manifest.json --channel $CHANNEL"
