#!/usr/bin/env python3
"""Edit details of an existing Gitea pull request.

Usage:
    edit_pr.py <pr_number> --title "New Title"
    edit_pr.py <pr_number> --body "New description"
    edit_pr.py <pr_number> --state closed
"""
import os
import sys
import json
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="Edit details of a Gitea pull request.")
    add_remote_args(parser)
    parser.add_argument("pr_number", type=int, help="PR number to edit.")
    parser.add_argument("--title", help="New PR title.")
    parser.add_argument("--body", help="New PR description.")
    parser.add_argument("--body-file", help="Read new PR body from this file ('-' for stdin).")
    parser.add_argument("--state", choices=["open", "closed"], help="Set PR state.")
    parser.add_argument("--base", help="Target branch name.")
    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

    body = args.body
    if args.body_file:
        if args.body_file == "-":
            body = sys.stdin.read()
        else:
            with open(args.body_file, "r", encoding="utf-8") as fh:
                body = fh.read()

    payload = {}
    if args.title is not None:
        payload["title"] = args.title
    if body is not None:
        payload["body"] = body
    if args.state is not None:
        payload["state"] = args.state
    if args.base is not None:
        payload["base"] = args.base

    if not payload:
        print("Error: At least one field to edit (--title, --body, --body-file, --state, --base) must be specified.", file=sys.stderr)
        return 1

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

    try:
        pr = api_request("PATCH", url, auth, payload)
        print(f"PR #{pr['number']} updated: {pr['html_url']}")
        print(f"Title: {pr['title']}")
        print(f"Status: {pr['state']}")
        print(f"Target Branch: {pr['base']['ref']}")
        return 0
    except Exception as e:
        print(f"Error editing PR #{args.pr_number}: {e}", file=sys.stderr)
        return 1


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