"""
BuddyGeo + Python (geopy drop-in & async /v1/batch) examples.

Install:
    pip install geopy requests

Usage:
    export BUDDYGEO_API_KEY="bg_live_your_key_here"
    python3 geopy_buddygeo.py
"""

from __future__ import annotations

import os
import time
import requests
from geopy.geocoders import Nominatim

API_KEY = os.environ["BUDDYGEO_API_KEY"]
BASE_URL = os.environ.get("BUDDYGEO_API_URL", "https://www.buddygeo.com").rstrip("/")


def geopy_drop_in_example() -> None:
    """
    Swap public Nominatim (1 req/s, 403 blocks) to BuddyGeo's hosted
    /search & /reverse compatibility endpoints in 3 lines.
    """
    domain = BASE_URL.replace("https://", "").replace("http://", "")
    scheme = "https" if BASE_URL.startswith("https://") else "http"

    geolocator = Nominatim(
        domain=domain,
        scheme=scheme,
        user_agent="my-app/1.0",
        timeout=15,
    )
    # Inject X-API-Key header on every Nominatim-compatible request
    geolocator.headers["X-API-Key"] = API_KEY

    loc = geolocator.geocode("290 Bremner Boulevard, Toronto, Canada")
    print("[geopy forward]", loc.latitude, loc.longitude, "->", loc.address)

    rev = geolocator.reverse((43.6426, -79.3871))
    print("[geopy reverse]", rev.address)


def batch_geocode_example(addresses: list[dict[str, str]]) -> list[dict]:
    """
    Geocode hundreds or thousands of rows asynchronously via POST /v1/batch.
    Unmatched or invalid rows cost 0 credits.
    """
    headers = {"X-API-Key": API_KEY, "Content-Type": "application/json"}
    submit = requests.post(
        f"{BASE_URL}/v1/batch",
        headers=headers,
        json={"rows": addresses},
        timeout=30,
    )
    submit.raise_for_status()
    job_id = submit.json()["job_id"]
    print(f"[batch] Submitted {job_id} ({len(addresses)} rows)")

    while True:
        poll = requests.get(f"{BASE_URL}/v1/batch/{job_id}", headers=headers, timeout=30)
        poll.raise_for_status()
        payload = poll.json()
        if payload["status"] in ("completed", "partial", "failed", "cancelled"):
            print(f"[batch] Finished: status={payload['status']} counts={payload.get('counts')}")
            return payload.get("rows", [])
        time.sleep(1.0)


if __name__ == "__main__":
    geopy_drop_in_example()
    results = batch_geocode_example(
        [
            {"id": "1", "q": "290 Bremner Boulevard, Toronto, Canada"},
            {"id": "2", "q": "5 Avenue Anatole France, Paris, France"},
            {"id": "3", "q": "350 5th Avenue, New York, United States"},
        ]
    )
    for row in results:
        print(" ", row)
