#!/bin/bash
# Forgejo CLI helper - token-efficient output
set -e

CRED_FILE="${CRED_FILE:-$(dirname "$0")/../.credentials/services.env}"
source "$CRED_FILE"

CURL="curl -sk -H \"Authorization: token ${FORGEJO_TOKEN}\""

usage() {
  cat <<EOF
Usage: forgejo <command> [args]

Commands:
  repos [org]              List repos (optionally filter by org)
  files <owner/repo> [path] List files in repo (default: root)
  cat <owner/repo> <path>  Get file content
  issues <owner/repo>      List open issues
  prs <owner/repo>         List open pull requests
  branches <owner/repo>    List branches
  commits <owner/repo> [n] Recent commits (default: 10)
  search <query>           Search repos
  raw <endpoint>           Raw API call (e.g., /api/v1/user)
EOF
}

case "${1:-}" in
  repos)
    if [ -n "${2:-}" ]; then
      eval $CURL "${FORGEJO_URL}/api/v1/orgs/$2/repos" | grep -oP '"full_name":"\K[^"]+'
    else
      eval $CURL "${FORGEJO_URL}/api/v1/user/repos?limit=50" | grep -oP '"full_name":"\K[^"]+'
    fi
    ;;
  files)
    [ -z "${2:-}" ] && { echo "Usage: forgejo files <owner/repo> [path]"; exit 1; }
    path="${3:-.}"
    eval $CURL "${FORGEJO_URL}/api/v1/repos/$2/contents/${path}" | \
      grep -oP '("name":"\K[^"]+|"type":"\K[^"]+)' | paste - - | awk '{print $2 "\t" $1}'
    ;;
  cat)
    [ -z "${3:-}" ] && { echo "Usage: forgejo cat <owner/repo> <path>"; exit 1; }
    eval $CURL "${FORGEJO_URL}/api/v1/repos/$2/contents/$3" | \
      grep -oP '"content":"\K[^"]+' | base64 -d
    ;;
  issues)
    [ -z "${2:-}" ] && { echo "Usage: forgejo issues <owner/repo>"; exit 1; }
    eval $CURL "${FORGEJO_URL}/api/v1/repos/$2/issues?state=open" | \
      grep -oP '("number":\K\d+|"title":"\K[^"]+)' | paste - - | awk '{print "#" $1 " " $2}'
    ;;
  prs)
    [ -z "${2:-}" ] && { echo "Usage: forgejo prs <owner/repo>"; exit 1; }
    eval $CURL "${FORGEJO_URL}/api/v1/repos/$2/pulls?state=open" | \
      grep -oP '("number":\K\d+|"title":"\K[^"]+)' | paste - - | awk '{print "#" $1 " " $2}'
    ;;
  branches)
    [ -z "${2:-}" ] && { echo "Usage: forgejo branches <owner/repo>"; exit 1; }
    eval $CURL "${FORGEJO_URL}/api/v1/repos/$2/branches" | grep -oP '"name":"\K[^"]+'
    ;;
  commits)
    [ -z "${2:-}" ] && { echo "Usage: forgejo commits <owner/repo> [n]"; exit 1; }
    limit="${3:-10}"
    eval $CURL "${FORGEJO_URL}/api/v1/repos/$2/commits?limit=${limit}" | \
      grep -oP '("sha":"\K[^"]{7}|"message":"\K[^"]+)' | paste - - | head -${limit}
    ;;
  search)
    [ -z "${2:-}" ] && { echo "Usage: forgejo search <query>"; exit 1; }
    eval $CURL "${FORGEJO_URL}/api/v1/repos/search?q=$2" | grep -oP '"full_name":"\K[^"]+'
    ;;
  raw)
    [ -z "${2:-}" ] && { echo "Usage: forgejo raw <endpoint>"; exit 1; }
    eval $CURL "${FORGEJO_URL}$2"
    ;;
  *)
    usage
    ;;
esac
