#!/usr/bin/env bash
# git-list-remote: list files in a remote branch
# Usage: git-list-remote [remote_name] [branch] [repo_path]
#
# Defaults:
#   remote_name = origin
#   branch      = main (falls back to master if main missing)
#   repo_path   = DEFAPP env var or "defapp"
#
# Example:
#   git-list-remote origin main
#   git-list-remote origin main ./myrepo

set -euo pipefail

REMOTE_NAME="${1:-origin}"
BRANCH="${2:-}"
REPO_PATH="${3:-}"
DEFAPP="${DEFAPP:-defapp}"

if [[ -n "$REPO_PATH" ]]; then
    if [[ ! -d "$REPO_PATH" ]]; then
        echo "Error: directory not found: $REPO_PATH" >&2
        exit 1
    fi
    cd "$REPO_PATH"
elif [[ -d "$DEFAPP" ]]; then
    cd "$DEFAPP"
fi

# Ensure we have remote refs
git fetch "$REMOTE_NAME" --quiet || true

# Default branch: try main, else master
if [[ -z "$BRANCH" ]]; then
    if git rev-parse --verify --quiet "$REMOTE_NAME/main" >/dev/null 2>&1; then
        BRANCH="main"
    elif git rev-parse --verify --quiet "$REMOTE_NAME/master" >/dev/null 2>&1; then
        BRANCH="master"
    else
        echo "Error: no default branch found for remote '$REMOTE_NAME'." >&2
        exit 1
    fi
fi

REF="$REMOTE_NAME/$BRANCH"

if ! git rev-parse --verify --quiet "$REF" >/dev/null 2>&1; then
    echo "Error: ref not found: $REF" >&2
    exit 1
fi

git ls-tree -r "$REF" --name-only
