import argparse
import json
import urllib.request
import os
import sys

def close_issue(issue_number, repo="yangyangxie/cortex-hub"):
    token = os.getenv("GITBUCKET_TOKEN")
    if not token:
        # Try to load from .env.gitbucket
        env_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), ".env.gitbucket")
        if os.path.exists(env_path):
            with open(env_path, 'r') as f:
                for line in f:
                    if line.startswith("GITBUCKET_TOKEN="):
                        token = line.split("=")[1].strip()
                        break
    
    if not token:
        print("Error: GITBUCKET_TOKEN not found in environment or .env.gitbucket.")
        sys.exit(1)

    url = f"https://gitbucket.jerxie.com/api/v3/repos/{repo}/issues/{issue_number}"
    data = {"state": "close"} # GitBucket uses 'open' or 'close' in some versions, or 'closed' in others. 
    # Let's try 'close' first as seen in some GitBucket API refs.

    req = urllib.request.Request(url, json.dumps(data).encode("utf-8"), headers={
        "Authorization": f"token {token}",
        "Content-Type": "application/json"
    }, method="PATCH")

    try:
        with urllib.request.urlopen(req) as response:
            print(f"Issue #{issue_number} has been closed.")
    except Exception as e:
        print(f"Error closing issue: {e}")
        if hasattr(e, 'read'):
            print(e.read().decode())
        
        # Second attempt with 'closed'
        print("Trying with state='closed'...")
        data = {"state": "closed"}
        req = urllib.request.Request(url, json.dumps(data).encode("utf-8"), headers={
            "Authorization": f"token {token}",
            "Content-Type": "application/json"
        }, method="PATCH")
        try:
            with urllib.request.urlopen(req) as response:
                print(f"Issue #{issue_number} has been closed (state=closed).")
        except Exception as e2:
             print(f"Failed again: {e2}")
             if hasattr(e2, 'read'):
                print(e2.read().decode())
             sys.exit(1)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Close a GitBucket issue.")
    parser.add_argument("--issue", required=True, type=int, help="Issue number")
    parser.add_argument("--repo", default="yangyangxie/cortex-hub", help="Repository (owner/repo)")
    
    args = parser.parse_args()
    close_issue(args.issue, args.repo)
