"""
QuarterBit
==========

Memory-efficient optimizer for PyTorch.

Usage:
    from quarterbit import Axiom
    optimizer = Axiom(model.parameters(), lr=1e-3)

Copyright (c) 2026 Clouthier Simulation Labs. All rights reserved.
"""

__version__ = "4.0.3"
__author__ = "Kyle Clouthier"

# Handle missing torch gracefully
try:
    from .torch.optim import Axiom
    __all__ = ['Axiom']
except ImportError as e:
    if 'torch' in str(e).lower():
        print("\n\033[93mQuarterBit requires PyTorch\033[0m")
        print("Install: \033[96mpip install torch\033[0m")
        print("Or with CUDA: \033[96mpip install torch --index-url https://download.pytorch.org/whl/cu121\033[0m\n")
    raise


def _check_license():
    """Check if license key is configured, show registration message if not."""
    import os
    import tempfile
    from pathlib import Path

    # Skip if already shown recently (once per week)
    cache_file = Path(tempfile.gettempdir()) / '.quarterbit_license_check'
    try:
        if cache_file.exists():
            import time
            if time.time() - cache_file.stat().st_mtime < 604800:  # 7 days
                return
    except:
        pass

    # Check for license key
    license_key = os.environ.get('QUARTERBIT_LICENSE_KEY', '')

    if not license_key:
        print("\n\033[96m" + "=" * 50 + "\033[0m")
        print("\033[1mWelcome to QuarterBit AXIOM!\033[0m")
        print("\033[96m" + "=" * 50 + "\033[0m")
        print("\nGet your \033[92mFREE license key\033[0m to activate:")
        print("  \033[96mhttps://quarterbit.dev/register\033[0m")
        print("\nThen set it:")
        print("  \033[93mexport QUARTERBIT_LICENSE_KEY=your-key-here\033[0m")
        print("\nFree tier: Personal use, research, <10 GPU-hrs/month")
        print("\033[96m" + "=" * 50 + "\033[0m\n")

        # Update cache
        try:
            cache_file.write_text('shown')
        except:
            pass


def _check_for_updates():
    """Check PyPI for newer version (runs in background thread)."""
    import os
    import threading

    # Skip if disabled
    if os.environ.get('QUARTERBIT_NO_UPDATE_CHECK', '').lower() in ('1', 'true', 'yes'):
        return

    def check():
        try:
            import json
            import urllib.request
            import tempfile
            import time
            from pathlib import Path

            # Cache file to avoid checking too often (once per day)
            cache_file = Path(tempfile.gettempdir()) / '.quarterbit_update_check'

            # Check if we already checked today
            if cache_file.exists():
                try:
                    cache_time = cache_file.stat().st_mtime
                    if time.time() - cache_time < 86400:  # 24 hours
                        return
                except:
                    pass

            # Query PyPI
            url = 'https://pypi.org/pypi/quarterbit/json'
            req = urllib.request.Request(url, headers={'User-Agent': 'quarterbit-update-check'})
            with urllib.request.urlopen(req, timeout=3) as response:
                data = json.loads(response.read().decode())
                latest = data['info']['version']

            # Update cache
            try:
                cache_file.write_text(latest)
            except:
                pass

            # Compare versions
            def parse_version(v):
                return tuple(int(x) for x in v.split('.')[:3])

            current = parse_version(__version__)
            latest_parsed = parse_version(latest)

            if latest_parsed > current:
                print(f"\n\033[93mQuarterBit {latest} available\033[0m (you have {__version__})")
                print(f"Upgrade: \033[96mpip install --upgrade quarterbit\033[0m\n")

        except:
            # Silently fail - don't interrupt user's workflow
            pass

    # Run in background thread
    thread = threading.Thread(target=check, daemon=True)
    thread.start()


# Run checks on import
_check_license()
_check_for_updates()
