import requests
import os
import json
from tkinter import Tk, Label, Entry, Button, Listbox, Scrollbar, END, StringVar, messagebox, Toplevel
from tkinter.ttk import Progressbar
from threading import Thread

CONFIG_FILE = 'config.json'

# === Загрузка и сохранение конфигурации ===
def load_config():
    if not os.path.exists(CONFIG_FILE):
        default_config = {
            "mc_version": "",
            "platform": "",
            "default_keywords": [],
            "download_folder": "mods",
            "user_agent": "ModPackBuilder/1.0 (+contact@yourdomain.com)"
        }
        with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
            json.dump(default_config, f, indent=4, ensure_ascii=False)
    with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
        return json.load(f)

def save_config(config):
    with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
        json.dump(config, f, indent=4, ensure_ascii=False)

# === API запросы и обработка ===
def search_mods(description, mc_version, platform, user_agent):
    url = 'https://api.modrinth.com/v2/search'
    headers = {'User-Agent': user_agent}
    facets = [
        [f"versions:{mc_version}"],
        [f"categories:{platform}"],
        ["project_type:mod"],
    ]
    params = {'query': description, 'facets': json.dumps(facets), 'limit': 20}
    response = requests.get(url, params=params, headers=headers)
    if response.status_code == 200:
        return response.json().get('hits', [])
    else:
        messagebox.showerror("Ошибка", f"Ошибка API: {response.status_code}")
        return []

def get_latest_compatible_version(mod_id, mc_version, user_agent):
    url = f'https://api.modrinth.com/v2/project/{mod_id}/version'
    headers = {'User-Agent': user_agent}
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        versions = [v for v in response.json() if mc_version in v['game_versions']]
        if versions:
            for version in versions:
                if version['version_type'] == 'release':
                    return version
            return versions[0]
    return None

def download_file(url, dest_folder, filename, progress_bar, user_agent):
    local_filename = os.path.join(dest_folder, filename)
    headers = {'User-Agent': user_agent}
    with requests.get(url, stream=True, headers=headers) as r:
        r.raise_for_status()
        total_size = int(r.headers.get('content-length', 0))
        with open(local_filename, 'wb') as f:
            downloaded = 0
            for chunk in r.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
                    downloaded += len(chunk)
                    progress_bar['value'] = (downloaded / total_size) * 100
                    progress_bar.update()
    return local_filename

# === GUI ===
class ModPackBuilder:
    def __init__(self, root, config):
        self.root = root
        self.config = config
        self.root.title("ModPack Builder")

        # === Поля для ввода данных ===
        self.mc_version_var = StringVar(value=config["mc_version"])
        self.platform_var = StringVar(value=config["platform"])
        self.description_var = StringVar(value=", ".join(config["default_keywords"]))

        Label(root, text="Версия Minecraft:").grid(row=0, column=0, sticky="w")
        Entry(root, textvariable=self.mc_version_var).grid(row=0, column=1)

        Label(root, text="Платформа (Forge/Fabric):").grid(row=1, column=0, sticky="w")
        Entry(root, textvariable=self.platform_var).grid(row=1, column=1)

        Label(root, text="Описание (ключевые слова):").grid(row=2, column=0, sticky="w")
        Entry(root, textvariable=self.description_var).grid(row=2, column=1)

        Button(root, text="Поиск модов", command=self.search_mods).grid(row=3, column=0, columnspan=2)

        # === Список модов ===
        self.mods_list = Listbox(root, selectmode="multiple", height=15, width=50)
        self.mods_list.grid(row=4, column=0, columnspan=2)
        self.scrollbar = Scrollbar(root, orient="vertical", command=self.mods_list.yview)
        self.scrollbar.grid(row=4, column=2, sticky="ns")
        self.mods_list.config(yscrollcommand=self.scrollbar.set)

        # === Кнопки ===
        Button(root, text="Скачать выбранные моды", command=self.download_selected_mods).grid(row=5, column=0, columnspan=2)

    def search_mods(self):
        description = self.description_var.get()
        mc_version = self.mc_version_var.get()
        platform = self.platform_var.get()

        self.config["mc_version"] = mc_version
        self.config["platform"] = platform
        self.config["default_keywords"] = description.split(", ")
        save_config(self.config)

        mods = search_mods(description, mc_version, platform, self.config["user_agent"])
        self.mods_list.delete(0, END)
        self.mods = mods
        for mod in mods:
            self.mods_list.insert(END, f"{mod['title']} - {mod['description']}")

    def download_selected_mods(self):
        selected_indices = self.mods_list.curselection()
        if not selected_indices:
            messagebox.showwarning("Предупреждение", "Выберите хотя бы один мод для скачивания.")
            return

        if not os.path.exists(self.config["download_folder"]):
            os.makedirs(self.config["download_folder"])

        self.progress_window = Toplevel(self.root)
        self.progress_window.title("Прогресс скачивания")

        progress_bar = Progressbar(self.progress_window, orient="horizontal", length=300, mode="determinate")
        progress_bar.pack(pady=20)

        def download():
            for idx in selected_indices:
                mod = self.mods[idx]
                version = get_latest_compatible_version(mod['project_id'], self.config["mc_version"], self.config["user_agent"])
                if version:
                    files = [file for file in version['files'] if file['primary']]
                    if files:
                        file_info = files[0]
                        filename = file_info['filename']
                        url = file_info['url']
                        download_file(url, self.config["download_folder"], filename, progress_bar, self.config["user_agent"])
                    else:
                        messagebox.showinfo("Информация", f"Нет файлов для мода {mod['title']}.")
                else:
                    messagebox.showinfo("Информация", f"Нет совместимых версий для мода {mod['title']}.")
            messagebox.showinfo("Готово", "Все моды скачаны!")
            self.progress_window.destroy()

        Thread(target=download).start()

# === Запуск приложения ===
if __name__ == '__main__':
    config = load_config()
    root = Tk()
    app = ModPackBuilder(root, config)
    root.mainloop()


добавь поддержку curseforge тоже сюда пж