import os
import platform
import sys
import tempfile
import urllib.request
import zipfile
from pathlib import Path

from setuptools import find_packages, setup
from setuptools.command.build_py import build_py

LIB_DIR = Path('nexaai/nexa_sdk/lib')
ARCHIVE = 'nexasdk-bridge.zip'


def detect_platform():
    version = os.getenv('NEXA_BRIDGE_VERSION', '').lstrip('v')
    if not version:
        with open('nexaai/_version.py', 'r', encoding='utf-8') as f:
            for line in f:
                if line.startswith('__version__'):
                    version = line.split('=')[1].strip().strip('\'"')
                    break
    if not version or version == '0.0.0':
        raise RuntimeError(f'Invalid version: {version}. Please ensure NEXA_BRIDGE_VERSION is set.')

    system = platform.system()
    arch = platform.machine().lower()

    os_name = 'macos' if system == 'Darwin' else system.lower()
    arch = 'x86_64' if arch in ('x86_64', 'amd64') else 'arm64'

    return version, os_name, arch


def download_and_extract():
    version, os_name, arch = detect_platform()
    url = (
        f'https://nexa-model-hub-bucket.s3.us-west-1.amazonaws.com/public/nexasdk/v{version}/{os_name}_{arch}/{ARCHIVE}'
    )

    if LIB_DIR.exists():
        return

    print(f'Downloading {url}...', file=sys.stderr, flush=True)

    with tempfile.TemporaryDirectory() as tmp:
        archive_path = Path(tmp) / ARCHIVE
        urllib.request.urlretrieve(url, archive_path)
        with zipfile.ZipFile(archive_path) as z:
            z.extractall(LIB_DIR)

    print('✓ Binaries installed', file=sys.stderr, flush=True)


class BuildWithBinary(build_py):
    _downloaded = False

    def run(self):
        if not os.getenv('NEXA_SKIP_DOWNLOAD'):
            if not BuildWithBinary._downloaded:
                try:
                    download_and_extract()
                    BuildWithBinary._downloaded = True
                except Exception as e:
                    print(f'ERROR: Failed to download binaries: {e}', file=sys.stderr, flush=True)
                    raise

        super().run()


setup(
    packages=find_packages(),
    cmdclass={
        'build_py': BuildWithBinary,
    },
    include_package_data=True,
)
