#!/usr/bin/env bash
# git-show-version: show content of a file at a given commit/ref
# Usage: git-show-version <ref> <path/to/file> [repo_path]
#
# ref can be: HEAD, HEAD~1, a SHA, a branch, a tag, origin/main, etc.
#
# Defaults:
#   repo_path = DEFAPP env var or "defapp"
#
# Example:
#   git-show-version HEAD src/index.php
#   git-show-version v1.2.0 config/app.conf
#   git-show-version origin/main README.md

set -euo pipefail

if [[ $# -lt 2 ]]; then
    echo "Usage: git-show-version <ref> <path/to/file> [repo_path]" >&2
    exit 1
fi

REF="$1"
FILE_PATH="$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

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

git show "$REF:$FILE_PATH"
