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

# Publish Vigthoria Workbench release artifacts + manifest.
# Usage:
#   HOST_DOWNLOADS_DIR=/path/to/releases \
#   HOST_MANIFEST_FILE=/path/to/releases/workbench-manifest.json \
#   ./scripts/release/publish-workbench-release.sh 0.2.0

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

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

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

"$REPO_ROOT/scripts/release/validate-powershell-installers.sh" "$REPO_ROOT/install.ps1"

install -d "$HOST_DOWNLOADS_DIR"

# Source tarball for Windows/macOS local build
SRC_TGZ="$REPO_ROOT/vigthoria-workbench-${VERSION}-source.tgz"
tar -czf "$SRC_TGZ" \
  --exclude=node_modules \
  --exclude=src-tauri/target \
  --exclude=dist \
  -C "$REPO_ROOT" \
  package.json package-lock.json vite.config.ts tsconfig.json tsconfig.node.json index.html install.ps1 README.md src src-tauri scripts

SHA_SRC="$(sha256sum "$SRC_TGZ" | awk '{print $1}')"
cp -f "$SRC_TGZ" "$HOST_DOWNLOADS_DIR/"
echo "Published source: $SRC_TGZ"

# Linux .deb if built
DEB=$(find "$REPO_ROOT/src-tauri/target/release/bundle/deb" -name "*_${VERSION}_*.deb" 2>/dev/null | head -1 || true)
if [[ -z "$DEB" || ! -f "$DEB" ]]; then
  DEB=$(find "$REPO_ROOT/src-tauri/target/release/bundle/deb" -name '*.deb' 2>/dev/null | sort -V | tail -1 || true)
fi
DEB_SHA=""
DEB_URL=""
if [[ -n "$DEB" && -f "$DEB" ]]; then
  DEB_NAME="vigthoria-workbench-${VERSION}-amd64.deb"
  cp -f "$DEB" "$HOST_DOWNLOADS_DIR/$DEB_NAME"
  DEB_SHA="$(sha256sum "$HOST_DOWNLOADS_DIR/$DEB_NAME" | awk '{print $1}')"
  DEB_URL="$PUBLIC_BASE_URL/$DEB_NAME"
  echo "Published deb: $DEB_NAME"
fi

# Windows NSIS setup (prebuilt - end users never compile locally)
WIN_SETUP=""
WIN_SHA=""
WIN_URL=""
for candidate in \
  "$REPO_ROOT/vigthoria-workbench-${VERSION}-x64-setup.exe" \
  "$REPO_ROOT/src-tauri/target/release/bundle/nsis/"*-setup.exe \
  "$REPO_ROOT/src-tauri/target/x86_64-pc-windows-gnu/release/bundle/nsis/"*-setup.exe; do
  if [[ -f "$candidate" ]]; then
    WIN_SETUP="$candidate"
    break
  fi
done
if [[ -n "$WIN_SETUP" && -f "$WIN_SETUP" ]]; then
  WIN_NAME="vigthoria-workbench-${VERSION}-x64-setup.exe"
  cp -f "$WIN_SETUP" "$HOST_DOWNLOADS_DIR/$WIN_NAME"
  WIN_SHA="$(sha256sum "$HOST_DOWNLOADS_DIR/$WIN_NAME" | awk '{print $1}')"
  WIN_URL="$PUBLIC_BASE_URL/$WIN_NAME"
  echo "Published Windows setup: $WIN_NAME"
else
  echo "WARN: No Windows setup.exe found. Run GitHub Actions windows-release workflow for NSIS."
fi

# Windows portable zip (cross-build from Linux - no NSIS required)
WIN_ZIP=""
WIN_ZIP_SHA=""
WIN_ZIP_URL=""
PORTABLE="$REPO_ROOT/vigthoria-workbench-${VERSION}-win64-portable.zip"
if [[ ! -f "$PORTABLE" && -f "$REPO_ROOT/src-tauri/target/x86_64-pc-windows-gnu/release/vigthoria-workbench.exe" ]]; then
  bash "$REPO_ROOT/scripts/release/package-windows-portable.sh"
fi
if [[ -f "$PORTABLE" ]]; then
  WIN_ZIP_NAME="vigthoria-workbench-${VERSION}-win64-portable.zip"
  cp -f "$PORTABLE" "$HOST_DOWNLOADS_DIR/$WIN_ZIP_NAME"
  WIN_ZIP_SHA="$(sha256sum "$HOST_DOWNLOADS_DIR/$WIN_ZIP_NAME" | awk '{print $1}')"
  WIN_ZIP_URL="$PUBLIC_BASE_URL/$WIN_ZIP_NAME"
  echo "Published Windows portable: $WIN_ZIP_NAME"
fi

python3 - << PYEOF
import json, pathlib
manifest_path = pathlib.Path(r"$HOST_MANIFEST_FILE")
data = {"channels": {}} if not manifest_path.exists() else json.loads(manifest_path.read_text())
data.setdefault("channels", {})
entry = {
  "version": "$VERSION",
  "notes": "Vigthoria Workbench ${VERSION} - multi-terminal workspace, CLI auth, comfort prompt, Hyper-Loop and Template tools. Windows: portable zip or Install-Vigthoria-Workbench.ps1 from extension.vigthoria.io. Requires vigthoria-cli for agent terminals and Hyper-Loop.",
  "source": {
    "url": "$PUBLIC_BASE_URL/vigthoria-workbench-${VERSION}-source.tgz",
    "sha256": "$SHA_SRC"
  },
  "platforms": {}
}
if "$DEB_URL":
  entry["platforms"]["linux-deb"] = {"url": "$DEB_URL", "sha256": "$DEB_SHA"}
if "$WIN_URL":
  entry["platforms"]["windows-setup"] = {"url": "$WIN_URL", "sha256": "$WIN_SHA"}
if "$WIN_ZIP_URL":
  entry["platforms"]["windows-portable"] = {"url": "$WIN_ZIP_URL", "sha256": "$WIN_ZIP_SHA"}
if "$CHANNEL" == "stable":
  win = {
    "install": "Download Vigthoria-Workbench-Windows-Setup.zip from extension.vigthoria.io, run Install-Vigthoria-Workbench.bat",
    "requires": ["WebView2 (usually preinstalled on Windows 10/11)", "vigthoria-cli for agent, login, and Hyper-Loop tools"]
  }
  if "$WIN_URL":
    win["setupExe"] = "$WIN_URL"
  entry["windows"] = win
data["channels"]["$CHANNEL"] = entry
manifest_path.write_text(json.dumps(data, indent=2) + "\n")
print("Manifest updated:", manifest_path)
PYEOF

echo "Done."
