#!/usr/bin/env python3
"""View details of a Gitea pull request.

Usage:
    view_pr.py <pr_number>
    view_pr.py --remote prgs 12
"""
import os
import sys
import argparse

# Auto-execute using the project's local virtual environment Python
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
venv_python = os.path.join(PROJECT_ROOT, "venv", "bin", "python3")
if os.path.exists(venv_python) and sys.executable != venv_python:
    os.execv(venv_python, [venv_python] + sys.argv)

from gitea_auth import get_auth_header, resolve_remote, add_remote_args, api_request, repo_api_url


def main(argv=None):
    parser = argparse.ArgumentParser(description="View details of a Gitea pull request.")
    add_remote_args(parser)
    parser.add_argument("pr_number", type=int, help="PR number to view.")
    args = parser.parse_args(argv)

    host, org, repo = resolve_remote(args)
    auth = get_auth_header(host)
    if not auth:
        print(f"Could not get credentials or token for {host}.", file=sys.stderr)
        return 1

    url = f"{repo_api_url(host, org, repo)}/pulls/{args.pr_number}"

    try:
        pr = api_request("GET", url, auth)
        print(f"PR #{pr['number']}: {pr['title']}")
        print(f"Status: {pr['state']}")
        print(f"Created by: {pr.get('user', {}).get('login', 'unknown')}")
        print(f"Branches: {pr['head']['ref']} -> {pr['base']['ref']}")
        print(f"Mergeable: {pr.get('mergeable')}")
        print(f"URL: {pr['html_url']}")
        print("\nDescription:")
        print(pr.get("body") or "(No description)")
        return 0
    except Exception as e:
        print(f"Error viewing PR #{args.pr_number}: {e}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
