#!/usr/bin/env python3
import requests
import sys
import datetime

# ================= KONFIGURÁCIÓ =================
BASE_URL = "http://gitea:3000/api/v1"
OWNER = "kincses"
REPO = "service-finder"
TOKEN = "783f58519ee0ca060491dbc07f3dde1d8e48c5dd"

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

# A teljes profi címkerendszer
LABELS = {
    "Status: To Do": "#ef4444", "Status: In Progress": "#f59e0b", "Status: Done": "#10b981", "Status: Blocked": "#000000",
    "Scope: Backend": "#0369a1", "Scope: Frontend": "#0284c7", "Scope: API": "#0ea5e9", "Scope: Core": "#38bdf8", "Scope: Robot": "#7dd3fc",
    "Type: Script": "#8b5cf6", "Type: Model": "#3b82f6", "Type: Database": "#ec4899", "Type: Bug": "#dc2626", "Type: Feature": "#16a34a",
    "Role: Admin": "#fb923c", "Role: User": "#fdba74"
}
# ================================================

def init_labels():
    """Lekéri a meglévő címkéket, és létrehozza a hiányzókat."""
    url = f"{BASE_URL}/repos/{OWNER}/{REPO}/labels"
    res = requests.get(url, headers=HEADERS)
    existing = {l['name']: l['id'] for l in res.json()} if res.status_code == 200 else {}
    
    label_ids = {}
    for name, color in LABELS.items():
        if name in existing:
            label_ids[name] = existing[name]
        else:
            post_res = requests.post(url, headers=HEADERS, json={"name": name, "color": color})
            if post_res.status_code == 201: label_ids[name] = post_res.json()['id']
    return label_ids

def set_issue_state(issue_num, new_state_label, category_labels=[]):
    label_ids = init_labels()
    res = requests.get(f"{BASE_URL}/repos/{OWNER}/{REPO}/issues/{issue_num}/labels", headers=HEADERS)
    current_ids = [l['id'] for l in res.json()] if res.status_code == 200 else []
    
    for status in ["Status: To Do", "Status: In Progress", "Status: Done", "Status: Blocked"]:
        if status in label_ids and label_ids[status] in current_ids:
            current_ids.remove(label_ids[status])
            
    if new_state_label in label_ids and label_ids[new_state_label] not in current_ids:
        current_ids.append(label_ids[new_state_label])
        
    for cat in category_labels:
        if cat in label_ids and label_ids[cat] not in current_ids:
            current_ids.append(label_ids[cat])

    requests.put(f"{BASE_URL}/repos/{OWNER}/{REPO}/issues/{issue_num}/labels", headers=HEADERS, json={"labels": current_ids})

def add_comment(issue_num, message):
    requests.post(f"{BASE_URL}/repos/{OWNER}/{REPO}/issues/{issue_num}/comments", headers=HEADERS, json={"body": message})

def create_issue(title, body, categories, milestone_id=None):
    url = f"{BASE_URL}/repos/{OWNER}/{REPO}/issues"
    payload = {"title": title, "body": body}
    if milestone_id is not None and milestone_id != "":
        try:
            payload["milestone"] = int(milestone_id)
        except ValueError:
            print(f"Figyelmeztetés: Érvénytelen milestone_id: {milestone_id}, figyelmen kívül hagyva.")
    res = requests.post(url, headers=HEADERS, json=payload)
    if res.status_code == 201:
        issue_num = res.json()['number']
        set_issue_state(issue_num, "Status: To Do", categories)
        print(f"Siker: #{issue_num} feladat létrehozva.")
        return True
    return False

def start_issue(issue_num):
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    set_issue_state(issue_num, "Status: In Progress")
    requests.post(f"{BASE_URL}/repos/{OWNER}/{REPO}/issues/{issue_num}/stopwatch/start", headers=HEADERS)
    add_comment(issue_num, f"▶️ **Munka megkezdve:** {now}")
    print(f"Siker: A #{issue_num} időmérése elindult.")

def finish_issue(issue_num, custom_message=None):
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    set_issue_state(issue_num, "Status: Done")
    requests.post(f"{BASE_URL}/repos/{OWNER}/{REPO}/issues/{issue_num}/stopwatch/stop", headers=HEADERS)
    requests.patch(f"{BASE_URL}/repos/{OWNER}/{REPO}/issues/{issue_num}", headers=HEADERS, json={"state": "closed"})
    
    # Itt adjuk hozzá az egyedi AI összefoglalót, ha van
    if custom_message:
        comment_body = f"✅ **Munka befejezve:** {now}\n\n**Technikai Összefoglaló:**\n{custom_message}\n\n⏱️ *A ráfordított időt a Gitea rögzítette.*"
    else:
        comment_body = f"✅ **Munka befejezve:** {now}\n⏱️ *A ráfordított időt a Gitea rögzítette.*"
        
    add_comment(issue_num, comment_body)
    print(f"Siker: A #{issue_num} lezárva, időmérés megállítva. Komment mentve.")

def get_issue(issue_num):
    url = f"{BASE_URL}/repos/{OWNER}/{REPO}/issues/{issue_num}"
    res = requests.get(url, headers=HEADERS)
    
    if res.status_code != 200:
        print(f"Hiba: Nem sikerült lekérni a #{issue_num} feladatot. Státusz kód: {res.status_code}")
        sys.exit(1)
    
    data = res.json()
    title = data.get('title', 'Nincs cím')
    body = data.get('body', 'Nincs leírás')
    state = data.get('state', 'unknown')
    created_at = data.get('created_at', '')
    updated_at = data.get('updated_at', '')
    
    print("=" * 60)
    print(f"Feladat #{issue_num} - {state.upper()}")
    print("=" * 60)
    print(f"Cím: {title}")
    print(f"Létrehozva: {created_at}")
    print(f"Frissítve: {updated_at}")
    print("-" * 60)
    print("Leírás:")
    print(body)
    print("=" * 60)

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Használat: python3 gitea_manager.py [start|finish|create|get] ...")
        print("  start <issue_num>")
        print("  finish <issue_num> [\"Custom summary message\"]")
        print("  get <issue_num>")
        print("  create \"<title>\" \"<body>\" [milestone_id] [category1 category2 ...]")
        sys.exit(1)

    action = sys.argv[1].lower()

    if action == "start":
        start_issue(sys.argv[2])
    elif action == "finish":
        # Ha van 3. paraméter (az üzenet), adjuk át
        custom_msg = sys.argv[3] if len(sys.argv) > 3 else None
        finish_issue(sys.argv[2], custom_msg)
    elif action == "create":
        title = sys.argv[2]
        body = sys.argv[3]
        milestone_id = None
        categories = []
        if len(sys.argv) > 4:
            arg4 = sys.argv[4]
            if arg4.isdigit():
                milestone_id = arg4
                categories = sys.argv[5:] if len(sys.argv) > 5 else []
            else:
                categories = sys.argv[4:]
        create_issue(title, body, categories, milestone_id)
    elif action == "get":
        get_issue(sys.argv[2])