#!/bin/bash
# deploy_public.sh — Deploy public files from main to the Forgejo public branch
#
# Usage: ./deploy_public.sh ["optional commit message"]
#
# Checks out an orphan public branch, copies the public files from main,
# generates a public README (stripping private sections), commits, and
# force-pushes to origin. Then switches back to main.
#
# E.M.F. February 2026

set -e

# --- Configuration ---

# Files to include on the public branch
PUBLIC_FILES=(
    build_store.py
    query_hybrid.py
    retrieve.py
    search_keywords.py
    run_query.sh
    clippings_search/build_clippings.py
    clippings_search/retrieve_clippings.py
    requirements.txt
    .gitignore
    LICENSE
)

REMOTE="origin"
BRANCH="public"
COMMIT_MSG="${1:-Update public branch from main}"

# --- Safety checks ---

CURRENT=$(git branch --show-current)
if [ "$CURRENT" != "main" ]; then
    echo "Error: must be on main branch (currently on $CURRENT)"
    exit 1
fi

if ! git diff --quiet HEAD 2>/dev/null; then
    echo "Error: uncommitted changes on main. Commit or stash first."
    exit 1
fi

MAIN_HEAD=$(git rev-parse --short HEAD)

# --- Build public branch ---

echo "Deploying main ($MAIN_HEAD) -> $BRANCH..."

# Delete local public branch if it exists
git branch -D "$BRANCH" 2>/dev/null || true

# Create fresh orphan
git checkout --orphan "$BRANCH"
git rm -rf . >/dev/null 2>&1 || true

# Copy public files from main
for f in "${PUBLIC_FILES[@]}"; do
    git checkout main -- "$f"
done

# Generate public README from main's README:
#   - Strip "## Notebooks" section
#   - Strip "## Development history" section
#   - Remove project-tree lines referencing private files
git checkout main -- README.md
awk '
/^## Notebooks/         { skip = 1; next }
/^## Development hist/  { skip = 1; next }
/^## /                  { skip = 0 }
skip                    { next }
/archived\//            { next }
/saved_output\//        { next }
/devlog\.txt/           { next }
/\*\.ipynb/             { next }
{ print }
' README.md > README.tmp && mv README.tmp README.md

# Stage and commit
git add .
git commit -m "$COMMIT_MSG

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>"

# Push
git push --force "$REMOTE" "$BRANCH"

# Switch back to main
git checkout main

echo ""
echo "Done. Deployed main ($MAIN_HEAD) -> $REMOTE/$BRANCH"
