import logging
import os

from src.core.config import settings

logger = logging.getLogger(__name__)

try:
    import geoip2.database
    import geoip2.errors
    _GEOIP_AVAILABLE = True
except ImportError:
    _GEOIP_AVAILABLE = False


def resolve_geoip(ip_address: str) -> dict:
    """Resolve IP to geo fields. Returns empty dict if unavailable or lookup fails."""
    if not _GEOIP_AVAILABLE or not ip_address:
        return {}
    db_path = getattr(settings, "MAXMIND_DB_PATH", None)
    if not db_path:
        return {}
    if not os.path.exists(db_path):
        logger.warning("MaxMind DB not found at %s — geo fields will be null", db_path)
        return {}
    try:
        with geoip2.database.Reader(db_path) as reader:
            response = reader.city(ip_address)
            return {
                "geo_city": response.city.name,
                "geo_region": response.subdivisions.most_specific.name,
                "geo_country": response.country.iso_code,
                "geo_isp": None,  # City DB does not include ISP; requires GeoLite2-ASN
            }
    except Exception as exc:
        logger.warning("GeoIP lookup failed for %s: %s", ip_address, exc)
        return {}
