#!/bin/bash
# pr-view.sh - View pull request details on GitHub or Gitea
# Usage: pr-view.sh -n <pr_number> [-r owner/repo]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/detect-platform.sh"

# Parse arguments
PR_NUMBER=""
REPO_OVERRIDE=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -n|--number)
            PR_NUMBER="$2"
            shift 2
            ;;
        -r|--repo)
            REPO_OVERRIDE="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: pr-view.sh -n <pr_number> [-r owner/repo]"
            echo ""
            echo "Options:"
            echo "  -n, --number   PR number (required)"
            echo "  -r, --repo     Repository slug (default: infer from git origin)"
            echo "  -h, --help     Show this help"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

if [[ -z "$PR_NUMBER" ]]; then
    echo "Error: PR number is required (-n)"
    exit 1
fi

if [[ -n "$REPO_OVERRIDE" ]]; then
    REPO_INFO="$REPO_OVERRIDE"
    PLATFORM=$(detect_platform 2>/dev/null || echo gitea)
else
    PLATFORM=$(detect_platform)
    REPO_INFO=$(get_repo_info)
fi

if [[ -z "$REPO_INFO" || "$REPO_INFO" == error:* ]]; then
    echo "Error: Could not determine repository from git origin. Run from a repo or pass --repo." >&2
    exit 1
fi

if [[ "$PLATFORM" == "github" ]]; then
    gh pr view "$PR_NUMBER" --repo "$REPO_INFO"
elif [[ "$PLATFORM" == "gitea" ]]; then
    if [[ -n "$REPO_OVERRIDE" ]]; then
        GITEA_LOGIN_NAME=$(get_gitea_login_for_repo_override) || {
            echo "Error: Could not resolve Gitea login for --repo override. Set GITEA_LOGIN or configure a default tea login." >&2
            exit 1
        }
    else
        GITEA_LOGIN_NAME=$(get_gitea_login) || {
            echo "Error: Could not resolve Gitea login for remote host" >&2
            exit 1
        }
    fi
    tea pr "$PR_NUMBER" --repo "$REPO_INFO" --login "$GITEA_LOGIN_NAME"
else
    echo "Error: Unknown platform"
    exit 1
fi
