import json
import urllib.request
import os

from dotenv import load_dotenv

load_dotenv(override=True)

# --- MANDATORY AUTH CONFIGURATION ---
GITEA_URL = "http://git.burke.lan:3000"  # No trailing slash
TOKEN = os.getenv("GITEA_TOKEN")
OWNER = "burkkyy"
REPO = "roadmap"
MILESTONE_ID = 1  

TASKS = [
    # {"title": "", "body": ""},
]

CHAPTERS = [
    "Ch.3",
    "Ch.4",
    "Ch.5",
    "Ch.6",
    "Ch.7",
    "Ch.8",
    "Ch.9",
    "Ch.10",
    "Ch.12",
    "Ch.13",
    "Ch.14",
]

for ch in CHAPTERS:
    TASKS.append({"title": f"{ch} - Problems", "body": f""})


headers = {
    "Authorization": f"token {TOKEN}",
    "Content-Type": "application/json",
    "Accept": "application/json"
}

url = f"{GITEA_URL}/api/v1/repos/{OWNER}/{REPO}/issues"

if not TASKS:
    print("Warning: 'TASKS' list is empty. Please populate your task templates before running.")
    exit(1)

for task in TASKS:
    title = task["title"]
    body = task["body"]
    
    payload = {
        "title": title,
        "body": body,
        "milestone": int(MILESTONE_ID)
    }
    
    data = json.dumps(payload).encode('utf-8')
    req = urllib.request.Request(url, data=data, headers=headers, method="POST")
    
    try:
        with urllib.request.urlopen(req) as response:
            if response.status == 201:
                print(f"Successfully created issue: {title}")
    except Exception as e:
        print(f"Failed to create issue '{title}': {e}")