"""Download latest GeoLite2-City.mmdb for offline GeoIP resolution.

Usage: runtime\python\python.exe scripts\download_geoip.py

Downloads the latest GeoLite2-City.mmdb from MaxMind's mirror (via
python-geoip-geolite2) and copies it to a non-Chinese path so the
maxminddb C extension can read it on Windows.

Requirements: python-geoip-geolite2, maxminddb
"""

from pathlib import Path
import os
import shutil
import subprocess
import sys


def main():
    print('Installing/updating python-geoip-geolite2...')
    subprocess.check_call([
        sys.executable, '-m', 'pip', 'install', '--upgrade',
        'python-geoip-geolite2', 'maxminddb',
    ])

    import _geoip_geolite2
    src = Path(_geoip_geolite2.__file__).parent / 'GeoLite2-City.mmdb'
    dst = Path(os.environ.get('TEMP', 'C:/temp')) / 'opencode' / 'GeoLite2-City.mmdb'

    dst.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(str(src), str(dst))
    print(f'Copied {src.name} ({src.stat().st_size / 1e6:.1f} MB)')
    print(f'  to {dst}')
    print('GeoIP database ready.')


if __name__ == '__main__':
    main()
