"""
GeoIP Service — تشخیص کشور از IP با استفاده از دیتابیس لوکال.

از GeoLite2 (MaxMind) استفاده می‌کند — بدون وابستگی آنلاین.
فایل دیتابیس: backend/data/geoip/GeoLite2-Country.mmdb
"""
import logging
from pathlib import Path

from django.conf import settings

logger = logging.getLogger('apps')

# Lazy load geoip2
_reader = None


def _get_reader():
    """بارگذاری lazy دیتابیس GeoIP."""
    global _reader
    if _reader is not None:
        return _reader

    try:
        import geoip2.database
    except ImportError:
        logger.warning("geoip2 package not installed. Install with: pip install geoip2")
        return None

    db_path = Path(settings.BASE_DIR) / 'data' / 'geoip' / 'GeoLite2-Country.mmdb'
    if not db_path.exists():
        logger.warning(f"GeoIP database not found at {db_path}")
        return None

    try:
        _reader = geoip2.database.Reader(str(db_path))
        logger.info(f"GeoIP database loaded from {db_path}")
        return _reader
    except Exception as e:
        logger.error(f"Failed to load GeoIP database: {e}")
        return None


def detect_country_from_ip(ip_address: str) -> dict | None:
    """
    تشخیص کشور از IP.
    
    Returns:
        dict: {iso_code, name} or None
    """
    if not ip_address:
        return None

    # Skip private/local IPs
    if ip_address in ('127.0.0.1', '::1', 'localhost') or ip_address.startswith('192.168.') or ip_address.startswith('10.'):
        return {'iso_code': 'IR', 'name': 'Iran'}  # Default for dev

    reader = _get_reader()
    if not reader:
        return None

    try:
        response = reader.country(ip_address)
        return {
            'iso_code': response.country.iso_code,
            'name': response.country.name,
        }
    except Exception as e:
        logger.debug(f"GeoIP lookup failed for {ip_address}: {e}")
        return None


def detect_country_for_request(request) -> str:
    """
    تشخیص کشور برای یک request — اولویت‌بندی:
    1. تنظیمات کاربر
    2. تنظیمات Tenant
    3. IP Geolocation
    4. Browser locale
    5. Default platform country
    """
    # 1. User preference
    if hasattr(request, 'user') and request.user.is_authenticated:
        try:
            pref = request.user.locale_preference
            if pref and pref.language:
                # Map language to country (rough)
                pass
        except Exception:
            pass

    # 2. Tenant settings
    tenant = getattr(request, 'tenant', None)
    if tenant:
        country_code = getattr(tenant, 'country', None)
        if country_code:
            return country_code

    # 3. IP Geolocation
    ip = _get_client_ip(request)
    if ip:
        result = detect_country_from_ip(ip)
        if result:
            return result['iso_code']

    # 4. Browser locale
    accept_lang = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
    if accept_lang:
        # Simple heuristic: fa → IR, en → US, ar → SA
        if accept_lang.startswith('fa'):
            return 'IR'
        elif accept_lang.startswith('ar'):
            return 'SA'

    # 5. Default
    return 'IR'


def _get_client_ip(request) -> str | None:
    """دریافت IP واقعی از request."""
    x_forwarded = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded:
        return x_forwarded.split(',')[0].strip()
    return request.META.get('REMOTE_ADDR')
