import os
import requests
import polyline
from flask import render_template, jsonify, request

GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY", "")
VALHALLA_URL = os.getenv("VALHALLA_URL", "http://localhost:8002")

SALLA_CENTER = {"lat": 66.8326, "lng": 28.6659}
SAMPLE_SERVICES = [
    {"id": 1, "name": "Salla Health Point", "type": "health", "lat": 66.8329, "lng": 28.6678, "address": "Salla center"},
    {"id": 2, "name": "Emergency Support Unit", "type": "health", "lat": 66.8380, "lng": 28.6532, "address": "Sallatunturintie area"},
    {"id": 3, "name": "Arctic Bike Repair", "type": "bike_repair", "lat": 66.8292, "lng": 28.6710, "address": "Town services area"},
    {"id": 4, "name": "Fell Rider Service", "type": "bike_repair", "lat": 66.8435, "lng": 28.6815, "address": "Tourism corridor"},
]


def _sq_distance(a_lat, a_lng, b_lat, b_lng):
    return (a_lat - b_lat) ** 2 + (a_lng - b_lng) ** 2


def _find_nearest(service_type, lat, lng):
    candidates = [s for s in SAMPLE_SERVICES if s["type"] == service_type]
    if not candidates:
        return None
    return min(candidates, key=lambda s: _sq_distance(lat, lng, s["lat"], s["lng"]))


@app.route("/map-demo")
def map_demo():
    return render_template(
        "map_demo.html",
        page_title="Salla Map Demo",
        google_maps_api_key=GOOGLE_MAPS_API_KEY,
        salla_center=SALLA_CENTER,
        sample_services=SAMPLE_SERVICES,
    )


@app.route("/api/services")
def api_services():
    return jsonify({"services": SAMPLE_SERVICES, "center": SALLA_CENTER})


@app.route("/api/nearest-service", methods=["POST"])
def api_nearest_service():
    data = request.get_json(force=True)
    service_type = data.get("service_type")
    lat = float(data.get("lat"))
    lng = float(data.get("lng"))
    nearest = _find_nearest(service_type, lat, lng)
    if not nearest:
        return jsonify({"error": "No matching service found"}), 404
    return jsonify({"nearest": nearest})


@app.route("/api/route", methods=["POST"])
def api_route():
    data = request.get_json(force=True)
    origin = data["origin"]
    destination = data["destination"]
    mode = data.get("mode", "bicycle")

    payload = {
        "locations": [
            {"lat": origin["lat"], "lon": origin["lng"]},
            {"lat": destination["lat"], "lon": destination["lng"]},
        ],
        "costing": mode,
        "directions_options": {"units": "kilometers"},
    }

    resp = requests.post(f"{VALHALLA_URL}/route", json=payload, timeout=20)
    resp.raise_for_status()
    route_json = resp.json()

    encoded = route_json["trip"]["legs"][0]["shape"]
    coords = polyline.decode(encoded, precision=6)
    path = [{"lat": lat, "lng": lng} for lat, lng in coords]

    summary = route_json["trip"]["summary"]
    return jsonify(
        {
            "path": path,
            "distance_km": round(summary.get("length", 0), 2),
            "duration_sec": summary.get("time", 0),
            "raw": route_json,
        }
    )
