"""
gguf2oom - Convert GGUF models to OomLlama's compact OOM format

Usage:
    gguf2oom model.gguf model.oom       # Convert GGUF to OOM Q2
    gguf2oom --info model.gguf          # Show GGUF file info

Expected compression:
    GGUF Q4_K (21 GB) → OOM Q2 (~8 GB)
    GGUF Q8_0 (42 GB) → OOM Q2 (~8 GB)

One love, one fAmIly! 🦙
"""

__version__ = "0.1.0"
__author__ = "Humotica AI Lab"

import os
import sys
import stat
import platform
import subprocess
import urllib.request
from pathlib import Path

# Binary download URLs
BINARY_URLS = {
    ("Linux", "x86_64"): "https://brein.jaspervandemeent.nl/downloads/gguf2oom-linux-x86_64",
    ("Linux", "aarch64"): "https://brein.jaspervandemeent.nl/downloads/gguf2oom-linux-aarch64",
    ("Darwin", "x86_64"): "https://brein.jaspervandemeent.nl/downloads/gguf2oom-macos-x86_64",
    ("Darwin", "arm64"): "https://brein.jaspervandemeent.nl/downloads/gguf2oom-macos-arm64",
}

def get_binary_path() -> Path:
    """Get the path where the binary should be stored."""
    cache_dir = Path.home() / ".cache" / "gguf2oom"
    cache_dir.mkdir(parents=True, exist_ok=True)

    system = platform.system()
    machine = platform.machine()

    # Normalize machine names
    if machine in ("AMD64", "x86_64"):
        machine = "x86_64"
    elif machine in ("arm64", "aarch64"):
        machine = "aarch64" if system == "Linux" else "arm64"

    suffix = ".exe" if system == "Windows" else ""
    return cache_dir / f"gguf2oom-{system.lower()}-{machine}{suffix}"


def download_binary() -> Path:
    """Download the gguf2oom binary for the current platform."""
    system = platform.system()
    machine = platform.machine()

    # Normalize
    if machine in ("AMD64", "x86_64"):
        machine = "x86_64"
    elif machine in ("arm64", "aarch64"):
        machine = "aarch64" if system == "Linux" else "arm64"

    key = (system, machine)
    if key not in BINARY_URLS:
        print(f"❌ Unsupported platform: {system} {machine}")
        print(f"   Supported: {list(BINARY_URLS.keys())}")
        print(f"\n   Download manually from:")
        print(f"   https://brein.jaspervandemeent.nl/downloads/")
        sys.exit(1)

    url = BINARY_URLS[key]
    binary_path = get_binary_path()

    if binary_path.exists():
        return binary_path

    print(f"🦙 Downloading gguf2oom for {system} {machine}...")
    print(f"   From: {url}")

    try:
        urllib.request.urlretrieve(url, binary_path)
        # Make executable
        binary_path.chmod(binary_path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
        print(f"   Saved to: {binary_path}")
        return binary_path
    except Exception as e:
        print(f"❌ Download failed: {e}")
        print(f"\n   Download manually from:")
        print(f"   {url}")
        sys.exit(1)


def main():
    """CLI entry point - runs the gguf2oom binary with all arguments."""
    binary = download_binary()

    # Pass all arguments to the binary
    args = sys.argv[1:]

    if not args:
        # Show help
        args = ["--help"]

    try:
        result = subprocess.run([str(binary)] + args)
        sys.exit(result.returncode)
    except KeyboardInterrupt:
        sys.exit(130)
    except Exception as e:
        print(f"❌ Error running gguf2oom: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
