"""
Map matching - phiên bản độc lập (không dùng aiohttp/homeassistant).
Nắn lộ trình GPS thô vào lưới đường thật bằng dịch vụ map hợp lệ.

Chỉ dùng server miễn phí (OSRM) nếu không có token Mapbox/Stadia.
"""
import math
import asyncio
import requests

_LOGGER_NAME = "vinfast.map_matching"

OSRM_SERVERS = [
    "https://routing.openstreetmap.de/routed-car",
    "http://router.project-osrm.org",
]

# ================= TOÁN HỌC =================

def haversine_distance(lat1, lon1, lat2, lon2):
    R = 6371000
    phi1, phi2 = math.radians(lat1), math.radians(lat2)
    dphi, dlambda = math.radians(lat2 - lat1), math.radians(lon2 - lon1)
    a = math.sin(dphi/2)**2 + math.cos(phi1)*math.cos(phi2)*math.sin(dlambda/2)**2
    return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))

def calculate_route_length(coords):
    if not coords or len(coords) < 2: return 0
    return sum(haversine_distance(coords[i][0], coords[i][1], coords[i+1][0], coords[i+1][1]) for i in range(len(coords)-1))

def moving_average_smooth(coords, window=3):
    """Làm trượt trung bình tọa độ để đường bớt răng cưa. Giữ nguyên cấu trúc [lat, lon, speed]."""
    if not coords or len(coords) < 3 or window < 2:
        return coords
    result = []
    half = window // 2
    for i in range(len(coords)):
        lat_s, lon_s = 0.0, 0.0
        cnt = 0
        for j in range(max(0, i-half), min(len(coords), i+half+1)):
            lat_s += coords[j][0]
            lon_s += coords[j][1]
            cnt += 1
        speed = coords[i][2] if len(coords[i]) > 2 else 0
        result.append([round(lat_s/cnt, 6), round(lon_s/cnt, 6), speed])
    return result

def _match_with_osrm(route):
    """Gọi dịch vụ Map Matching của OSRM cho cả chuỗi tọa độ. Trả về [ [lat,lon], ... ] hoặc None."""
    coords = [f"{c[1]},{c[0]}" for c in route]  # OSRM muốn lon,lat
    coord_str = ";".join(coords)
    for server in OSRM_SERVERS:
        try:
            url = f"{server}/match/v1/driving/{coord_str}?overview=full&geometries=geojson"
            res = requests.get(url, timeout=10)
            if res.status_code == 200:
                data = res.json()
                if data.get("code") == "Ok" and data.get("matchings"):
                    geometry = data["matchings"][0].get("geometry", {})
                    pts = geometry.get("coordinates", [])
                    if len(pts) > 2:
                        return [[p[1], p[0]] for p in pts]
        except Exception:
            continue
    return None

# Route nắn 완 bị bọc async để giữ tương thích lời gọi trong api.py
async def async_process_route(hass=None, route=None, mapbox_token="", stadia_token=""):
    """API giữ nguyên chữ ký với bản HA. Chạy sync bên trong thread riêng."""
    if not route or len(route) < 3:
        return route
    return await asyncio.to_thread(_match_route_sync, route, mapbox_token, stadia_token)

def _match_route_sync(route, mapbox_token="", stadia_token=""):
    """Ưu tiên Mapbox (nếu có token) -> Stadia -> OSRM miễn phí -> trả về bản làm mượt"""
    # Mapbox Map Matching (nếu user cấu hình token)
    try:
        if mapbox_token:
            coords = ";".join([f"{c[1]},{c[0]}" for c in route])
            url = ("https://api.mapbox.com/matching/v1/driving/{coords}?overview=full&geometries=geojson&access_token={tok}")
            url = url.format(coords=coords, tok=mapbox_token)
            res = requests.get(url, timeout=10)
            if res.status_code == 200:
                data = res.json()
                pts = data.get("matchings", [{}])[0].get("geometry", {}).get("coordinates", [])
                if len(pts) > 2:
                    return [[p[1], p[0]] for p in pts]
    except Exception:
        pass

    # Stadia (nếu có token)
    try:
        if stadia_token:
            coords = ";".join([f"{c[1]},{c[0]}" for c in route])
            url = f"https://api.stadiamaps.com/match/v1/driving/{coords}?api_key={stadia_token}"
            res = requests.get(url, timeout=10)
            if res.status_code == 200:
                data = res.json()
                pts = data.get("matchings", [{}])[0].get("geometry", {}).get("coordinates", [])
                if len(pts) > 2:
                    return [[p[1], p[0]] for p in pts]
    except Exception:
        pass

    # OSRM miễn phí
    matched = _match_with_osrm(route)
    if matched:
        return matched

    # Fallback: chỉ làm mượt tay
    return moving_average_smooth(route, window=5)
