#!/usr/bin/env bash

# Publish one reviewed HTML file to the Research Institute PRO OSS bucket.
# The bucket has server-side AES256 encryption enabled and remains private;
# it does not change ACLs or broaden access.

set -euo pipefail

bucket="research-institute-pro-1408992348164428"
endpoint="oss-cn-beijing.aliyuncs.com"
prefix="html"
public_base="https://${bucket}.${endpoint}/${prefix}"
aliyun_profile="${ALIYUN_PROFILE:-ai-nutrition-audit}"

usage() {
  printf 'Usage: %s <input.html> [published-name]\n' "${0##*/}"
}

input="${1:-}"
published_name="${2:-}"

if [[ -z "$input" || ! -f "$input" ]]; then
  usage >&2
  exit 2
fi

if [[ "${input##*.}" != "html" ]]; then
  printf 'ERROR: input must be an .html file: %s\n' "$input" >&2
  exit 2
fi

if [[ -z "$published_name" ]]; then
  published_name="$(basename "$input")"
fi

if [[ "$published_name" == /* || "$published_name" == *".."* || "$published_name" == */ || ! "$published_name" =~ ^[A-Za-z0-9._/-]+$ ]]; then
  printf 'ERROR: published name must be a safe relative object path: %s\n' "$published_name" >&2
  exit 2
fi

published_basename="${published_name##*/}"
if [[ "$published_basename" == *.* && "$published_basename" != *.html ]]; then
  printf 'ERROR: published HTML name must use .html or no extension: %s\n' "$published_name" >&2
  exit 2
fi

if rg -n 'file://|/Users/' "$input" >/dev/null; then
  printf 'ERROR: local file link found; replace it with an OSS or HTTPS URL before publishing: %s\n' "$input" >&2
  exit 1
fi

object="oss://${bucket}/${prefix}/${published_name}"
url="${public_base}/${published_name}"

aliyun --profile "$aliyun_profile" oss cp "$input" "$object" \
  --force \
  --meta 'Content-Type:text/html; charset=utf-8#Content-Disposition:inline#Cache-Control:no-cache' \
  --endpoint "$endpoint"

printf 'UPLOADED_PRIVATE %s\n' "$url"
