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

def create_issue(title, body, 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"
    # Support literal \n passed from shell
    body = body.replace("\\n", "\n")
    data = {"title": title, "body": body}

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

    try:
        with urllib.request.urlopen(req) as response:
            res = json.loads(response.read().decode())
            print(f"Created Issue #{res.get('number')} - {res.get('html_url')}")
            return res.get('number')
    except Exception as e:
        print(f"Error creating issue: {e}")
        if hasattr(e, 'read'):
            print(e.read().decode())
        sys.exit(1)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Create a GitBucket issue.")
    parser.add_argument("--title", required=True, help="Issue title")
    parser.add_argument("--body", required=True, help="Issue body markdown")
    parser.add_argument("--repo", default="yangyangxie/cortex-hub", help="Repository (owner/repo)")
    
    args = parser.parse_args()
    create_issue(args.title, args.body, args.repo)
