import requests
import sys
import zipfile
import shutil
from pathlib import Path

# הגדרות מערכת - נשאר בדיוק לפי ההנחיות שלך
API_URL = "https://api.github.com/repos/YairDaniel123/Otzarya-Library/releases/latest"
OTZARIA_LIB = Path(r"C:\ProgramData\otzaria\books")
TEMP_FILE = Path("download.tmp")
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
CHUNK_SIZE = 1024 * 1024

def get_remote_assets():
    try:
        r = requests.get(API_URL, headers=HEADERS, timeout=15)
        r.raise_for_status()
        data = r.json()
        assets = {}
        for a in data.get("assets", []):
            if not a["name"].endswith(".zip"):
                continue
            name = a.get("label") or a["name"]
            assets[name] = {
                "url": a["browser_download_url"],
                "updated": a["updated_at"],
                "is_full": (a["name"] == "full-library.zip")
            }
        return assets
    except Exception as e:
        print(f"ERROR:LIST|{str(e)}", flush=True)
        sys.exit(1)

def check_updates():
    if not OTZARIA_LIB.exists():
        try:
            OTZARIA_LIB.mkdir(parents=True, exist_ok=True)
        except Exception as e:
            print(f"ERROR:PERMISSION|{str(e)}", flush=True)
            return

    remote = get_remote_assets()
    results = []
    
    for name, info in remote.items():
        folder = name.replace(".zip", "")
        version_file = OTZARIA_LIB / folder / ".version_info"
        
        is_up_to_date = version_file.exists() and version_file.read_text(encoding="utf-8").strip() == info["updated"]
        
        if not is_up_to_date:
            type_id = "0" if info["is_full"] else "1"
            results.append(f"{type_id}|{name}|{info['url']}|{info['updated']}")
    
    if results:
        results.sort()
        print(f"LIST:{';'.join(results)}", flush=True)
    else:
        print("EMPTY", flush=True)

def download_and_extract(url, updated_at, display_name):
    try:
        with requests.get(url, stream=True, headers=HEADERS, timeout=(10, None)) as r:
            r.raise_for_status()
            total = int(r.headers.get("content-length", 0))
            done = 0
            with open(TEMP_FILE, "wb") as f:
                for chunk in r.iter_content(CHUNK_SIZE):
                    if chunk:
                        f.write(chunk)
                        done += len(chunk)
                        if total:
                            print(f"DL_PROGRESS:{int(done/total*100)}", flush=True)
        
        print("DL_FINISHED", flush=True)
        folder_name = display_name.replace(".zip", "")
        target_dir = OTZARIA_LIB / folder_name
        temp_extract = OTZARIA_LIB / f"temp_{folder_name}"
        
        if temp_extract.exists(): shutil.rmtree(temp_extract)
        temp_extract.mkdir(parents=True)
        
        with zipfile.ZipFile(TEMP_FILE, "r") as z:
            files = [f for f in z.namelist() if not f.endswith(".version_info")]
            for i, f in enumerate(files):
                z.extract(f, temp_extract)
                print(f"EX_PROGRESS:{int((i+1)/len(files)*100)}", flush=True)
        
        if target_dir.exists(): shutil.rmtree(target_dir)
        temp_extract.rename(target_dir)
        (target_dir / ".version_info").write_text(updated_at, encoding="utf-8")
        print("DONE", flush=True)
        
    except Exception as e:
        print(f"ERROR:PROCESS|{str(e)}", flush=True)
    finally:
        if TEMP_FILE.exists(): TEMP_FILE.unlink()

if __name__ == "__main__":
    if len(sys.argv) < 2: sys.exit()
    cmd = sys.argv[1]
    if cmd == "CHECK": check_updates()
    elif "|" in cmd:
        p = cmd.split("|")
        if len(p) >= 4: download_and_extract(p[2], p[3], p[1])