import os, re, requests

def _looks_like_coords(q):
    return bool(re.match(r"^\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*$", q))

def geocode_input(q):
    provider = (os.getenv("GEOCODER_PROVIDER","nominatim") or "nominatim").lower()
    if _looks_like_coords(q):
        lat, lon = [float(x.strip()) for x in q.split(",")]
        by_coords = True
    else:
        lat = lon = None
        by_coords = False

    if provider == "mapbox":
        token = os.getenv("MAPBOX_TOKEN")
        # Implement Mapbox geocoding here if token present
    elif provider == "google":
        api_key = os.getenv("GOOGLE_API_KEY")
        # Implement Google Geocoding here if key present

    # Default to Nominatim (be mindful of rate limits; add your email to headers)
    if by_coords:
        url = f"https://nominatim.openstreetmap.org/reverse"
        params = {"lat": lat, "lon": lon, "format": "json", "zoom": 14, "addressdetails": 1}
    else:
        url = f"https://nominatim.openstreetmap.org/search"
        params = {"q": q, "format": "json", "limit": 1, "addressdetails": 1}

    headers = {"User-Agent": "SignCodeScout/1.0 (your-email@example.com)"}
    r = requests.get(url, params=params, headers=headers, timeout=20)
    r.raise_for_status()
    data = r.json()

    if by_coords:
        addr = data.get("address", {})
    else:
        first = data[0] if data else {}
        addr = first.get("address", {})
        if first and "lat" in first and "lon" in first:
            lat = float(first["lat"]); lon = float(first["lon"])

    result = {
        "input_type": "coords" if by_coords else "address",
        "lat": lat, "lon": lon,
        "raw_address": addr,
        "city": addr.get("city") or addr.get("town") or addr.get("village"),
        "county": addr.get("county"),
        "state": addr.get("state"),
        "postcode": addr.get("postcode"),
        "country": addr.get("country"),
        "municipality": addr.get("city") or addr.get("town") or addr.get("village") or addr.get("county"),
        "zoning": None,  # to be enriched
    }
    return result
