"""
fitz_loader_whl.py
Charge dynamiquement PyMuPDF (fitz) depuis le .whl compatible avec l’OS, l’architecture et la version Python.
"""

import sys
import os
import platform
import tempfile
import zipfile
from calibre.utils.logging import default_log as log

def load_fitz_from_whl():
    """Charge dynamiquement la bonne version de PyMuPDF (fitz) depuis un fichier .whl."""

    major, minor = sys.version_info[:2]
    py_tag = f"cp{major}{minor}"
    system = platform.system().lower()
    arch = platform.machine().lower()

    # Détermination du tag d’OS et architecture
    if system.startswith("win"):
        if "64" in arch:
            os_tag = "win_amd64"
        else:
            os_tag = "win32"
    elif system.startswith("linux"):
        if "aarch" in arch or "arm" in arch:
            os_tag = "manylinux_aarch64"
        else:
            os_tag = "manylinux_x86_64"
    elif system.startswith("darwin"):
        os_tag = "macosx_arm64" if "arm" in arch else "macosx_x86_64"
    else:
        raise ImportError(f"Système non supporté : {system} ({arch})")

    whl_dir = os.path.join(os.path.dirname(__file__), "pymupdf_whls")
    if not os.path.exists(whl_dir):
        raise ImportError(f"Dossier non trouvé : {whl_dir}")

    # Recherche d’un .whl qui correspond au mieux
    whl_files = [f for f in os.listdir(whl_dir) if f.endswith(".whl")]
    if not whl_files:
        raise ImportError(f"Aucun fichier .whl trouvé dans {whl_dir}")

    selected_whl = None
    for whl in whl_files:
        if py_tag in whl and os_tag in whl:
            selected_whl = whl
            break

    # Tolérance : si on ne trouve pas exactement le bon, on prend cp39-abi3 compatible
    if not selected_whl:
        for whl in whl_files:
            if "abi3" in whl and os_tag in whl:
                selected_whl = whl
                break

    if not selected_whl:
        raise ImportError(f"Aucun .whl compatible trouvé pour {system} / {arch} / {py_tag}")

    whl_path = os.path.join(whl_dir, selected_whl)

    # Extraction temporaire
    tempdir = tempfile.TemporaryDirectory()
    with zipfile.ZipFile(whl_path, "r") as z:
        z.extractall(tempdir.name)

    sys.path.insert(0, tempdir.name)
    log.info(f"pdftocbz: {major}, {minor} , {py_tag} , {system} , {arch}, {selected_whl}")

    try:
        import fitz
        return fitz
    finally:
        sys.path.pop(0)
