import os
from django.conf import settings
import logging
import subprocess
from django.core.cache import cache

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

def request_to_region(request):
    ip = get_client_ip(request)
    if not ip:
        logging.warning("Cannot get client IP from request: %s" % request)
        return
    return ip_to_region(ip)

def ip_to_region(ip):
    ck = 'ip2region.' + ip
    region = cache.get(ck)
    if not region:
        cmd = [os.path.join(settings.BASE_DIR, "scripts/ip2region.py"), ip]
        try:
            out = subprocess.check_output(cmd).decode()
            seen = set()
            locs = []
            for u in out.split('|'):
                us = u.strip()
                if us not in ['', '0', '中国'] and us not in seen:
                    seen.add(us)
                    locs.append(us)
            region = '-'.join(locs)
        except Exception as e:
            region = "N/A"
        cache.set(ck, region)
    return region
