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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
STATUS_DIR="${ROOT_DIR}/status"
API_DIR="${ROOT_DIR}/dashcaddy-api"

log() { echo "[prepare-release] $*"; }
fail() { echo "[prepare-release] ERROR: $*" >&2; exit 1; }

[[ -f "${STATUS_DIR}/package.json" ]] || fail "Missing status/package.json"
[[ -f "${API_DIR}/package.json" ]] || fail "Missing dashcaddy-api/package.json"

log "Building dashboard frontend..."
cd "${STATUS_DIR}"
npm run build

log "Verifying CSP hash present in status/index.html..."
grep -q "Content-Security-Policy" "${STATUS_DIR}/index.html" || fail "Missing CSP meta tag"
grep -q "sha256-" "${STATUS_DIR}/index.html" || fail "Missing CSP script hash"
grep -q "license-topbar-version" "${STATUS_DIR}/index.html" || fail "Expected version-chip markup missing"

log "Verifying API version metadata..."
node -e "const fs=require('fs'); const pkg=JSON.parse(fs.readFileSync('${API_DIR}/package.json','utf8')); if(!pkg.version) process.exit(1); console.log('[prepare-release] API version', pkg.version);"

log "Release prep complete. Package from repo root after this step."
