"""Neighborhood discovery via spatial clustering (DBSCAN + Concave Hull).

Discovers organic, contiguous residential neighborhoods from filtered houses,
computes smooth physical boundary polygons (concave hulls), labels neighborhoods
intelligently with local streets, and computes composite livability & garden rankings.
"""

from __future__ import annotations

import json
import logging
from collections import Counter
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import duckdb
import numpy as np
from shapely import MultiPoint, MultiPolygon, Point, Polygon, concave_hull, STRtree

from ch_housing.density import (
    compute_median,
    format_street_view_html,
    format_street_view_url,
)
from ch_housing.viewshed import wgs84_to_lv95

logger = logging.getLogger(__name__)


def lv95_to_wgs84(easting: float, northing: float) -> Tuple[float, float]:
    """Convert Swiss LV95 (EPSG:2056) coordinates to WGS84 (lat, lon) in decimal degrees.
    
    Uses official Swisstopo high-precision projection polynomial formulas.
    """
    y_p = (easting - 2600000.0) / 1000000.0
    x_p = (northing - 1200000.0) / 1000000.0
    lon = (2.6779094 + 4.728982 * y_p + 0.791484 * y_p * x_p + 0.1306 * y_p * (x_p ** 2) - 0.0436 * (y_p ** 3)) * 100.0 / 36.0
    lat = (16.9023892 + 3.238272 * x_p - 0.270978 * (y_p ** 2) - 0.002528 * (x_p ** 2) - 0.0447 * (y_p ** 2) * x_p - 0.0140 * (x_p ** 3)) * 100.0 / 36.0
    return lat, lon


def calculate_livability_score(props: Dict[str, Any]) -> float:
    """Calculate composite Livability & Garden Index (0 to 100).
    
    Weights (100 pts total):
    - Private Garden & Green Ratio: 15 pts
    - Big City Commute Time & Cadence: 15 pts
    - Local Walkability (Transit, Restaurant, Supermarket, Gym, School, Daycare): 15 pts
    - Acoustic Quietness & Airport Peace: 15 pts
    - Road Safety & Calmed Lanes: 10 pts
    - Viewshed Panoramas (Lake & Mountain): 15 pts
    - Microclimate & Solar Exposure (Südhang): 10 pts
    - Municipal Tax Advantage: 5 pts
    """
    score = 0.0

    # 1. Garden & Greenery (up to 15 pts)
    garden_m2 = props.get("median_garden_m2", 0.0) or 0.0
    score += min(7.5, max(0.0, (garden_m2 - 100.0) / 300.0 * 7.5))
    green_ratio = props.get("median_green_ratio", 0.0) or 0.0
    score += min(7.5, max(0.0, (green_ratio - 0.35) / 0.35 * 7.5))

    # 2. Transit Commute, Cadence & Hops (up to 15 pts)
    commute_min = props.get("median_commute_min", 25.0) or 25.0
    score += max(0.0, min(8.0, (25.0 - commute_min) / 15.0 * 8.0))
    cadence_min = props.get("median_transit_cadence_min", 15.0) or 15.0
    score += max(0.0, min(4.0, (15.0 - cadence_min) / 10.0 * 4.0))
    hops = props.get("median_transit_hops")
    hops_val = float(hops) if hops is not None else 1.0
    if hops_val <= 0.2:
        score += 3.0  # Direct train/tram (0 transfers)
    elif hops_val <= 1.2:
        score += 1.5  # 1 hop (1 bus + 1 train)

    # 3. Local Walkability (up to 15 pts)
    walk_transit = props.get("median_walk_transit_min", 10.0) or 10.0
    score += max(0.0, min(3.0, (10.0 - walk_transit) / 6.0 * 3.0))
    walk_resto = props.get("median_walk_restaurant_min", 10.0) or 10.0
    score += max(0.0, min(3.0, (10.0 - walk_resto) / 5.0 * 3.0))
    walk_sm = props.get("median_walk_supermarket_min", 10.0) or 10.0
    score += max(0.0, min(3.0, (10.0 - walk_sm) / 5.0 * 3.0))
    walk_gym = props.get("median_walk_gym_min", 20.0) or 20.0
    score += max(0.0, min(2.0, (20.0 - walk_gym) / 10.0 * 2.0))
    walk_sc = props.get("median_walk_school_min", 12.0) or 12.0
    score += max(0.0, min(2.0, (12.0 - walk_sc) / 6.0 * 2.0))
    access_dc = props.get("median_daycare_access_min")
    if access_dc is None:
        access_dc = props.get("median_walk_daycare_min", 12.0) or 12.0
    score += max(0.0, min(2.0, (15.0 - float(access_dc)) / 7.5 * 2.0))

    # 4. Acoustic Quietness & Airport Peace (up to 15 pts)
    quietness = props.get("median_quietness_score", 50.0) or 50.0
    score += min(10.0, max(0.0, (quietness - 50.0) / 50.0 * 10.0))
    dist_airport = props.get("median_dist_airport_km", 5.0) or 5.0
    score += min(5.0, max(0.0, (dist_airport - 5.0) / 10.0 * 5.0))

    # 5. Road Safety & Calmed Lanes (up to 10 pts)
    road_safety = props.get("median_road_safety_score", 70.0) or 70.0
    score += min(7.0, max(0.0, (road_safety - 40.0) / 60.0 * 7.0))
    calm_ratio = props.get("calm_lanes_ratio", 0.0) or 0.0
    score += min(3.0, max(0.0, calm_ratio * 3.0))

    # 6. Viewshed (Lake & Mountain Panoramas) (up to 15 pts)
    lake_ratio = props.get("lake_view_ratio", 0.0) or 0.0
    score += lake_ratio * 8.0
    mtn_ratio = props.get("mountain_view_ratio", 0.0) or 0.0
    score += mtn_ratio * 7.0

    # 7. Microclimate & Solar Exposure (Südhang) (up to 10 pts)
    sun_score = props.get("median_sun_exposure_score", 70.0) or 70.0
    score += min(7.0, max(0.0, (sun_score - 40.0) / 60.0 * 7.0))
    if props.get("is_south_facing", False):
        score += 3.0

    # 8. Municipal Tax Advantage (up to 5 pts)
    tax_mult = props.get("tax_multiplier_pct", 75.0) or 75.0
    score += min(5.0, max(0.0, (100.0 - tax_mult) / 50.0 * 5.0))

    return round(min(100.0, max(0.0, score)), 1)


def subdivide_large_cluster(
    indices: List[int],
    coords: np.ndarray,
    max_size: int = 350,
) -> List[List[int]]:
    """Recursively bisect large contiguous settlements along their longest axis."""
    if len(indices) <= max_size:
        return [indices]

    sub = coords[indices]
    dx = sub[:, 0].max() - sub[:, 0].min()
    dy = sub[:, 1].max() - sub[:, 1].min()
    axis = 0 if dx >= dy else 1

    med = np.median(sub[:, axis])
    left = [i for i in indices if coords[i, axis] <= med]
    right = [i for i in indices if coords[i, axis] > med]

    if not left or not right:
        mid = len(indices) // 2
        left, right = indices[:mid], indices[mid:]

    return subdivide_large_cluster(left, coords, max_size) + subdivide_large_cluster(right, coords, max_size)


def discover_neighborhoods(
    houses: List[Dict[str, Any]],
    eps_m: float = 75.0,
    min_houses: int = 15,
    max_houses: int = 350,
    concave_ratio: float = 0.35,
    buffer_m: float = 25.0,
) -> List[Dict[str, Any]]:
    """Discover natural, contiguous residential neighborhoods using spatial clustering and concave hulls.
    
    Parameters:
    - houses: list of matching residential house records
    - eps_m: spatial connectivity threshold in meters (default 75m)
    - min_houses: minimum houses to qualify as a distinct neighborhood (default 15)
    - max_houses: maximum houses before bisecting contiguous urban sprawl (default 350)
    - concave_ratio: tightness of concave hull (0.0 to 1.0, default 0.35)
    - buffer_m: parcel envelope buffer radius in meters (default 25m)
    """
    if not houses:
        return []

    logger.info("Starting neighborhood discovery on %d candidate houses (eps=%.1fm, min=%d)...", len(houses), eps_m, min_houses)

    # 1. Coordinate extraction and validation
    cleaned_houses: List[Dict[str, Any]] = []
    lv95_coords: List[Tuple[float, float]] = []

    for h in houses:
        e = h.get("gkode")
        n = h.get("gkodn")
        if e is None or n is None or np.isnan(float(e)) or np.isnan(float(n)):
            lat = h.get("lat")
            lon = h.get("lon")
            if lat is not None and lon is not None:
                e, n = wgs84_to_lv95(float(lat), float(lon))
            else:
                continue
        cleaned_houses.append(h)
        lv95_coords.append((float(e), float(n)))

    if not cleaned_houses:
        return []

    coords_arr = np.array(lv95_coords, dtype=np.float64)

    # 2. Partition by postal code / municipality to maintain municipal identity
    postal_groups: Dict[str, List[int]] = {}
    for idx, h in enumerate(cleaned_houses):
        postal = str(h.get("postal_code") or h.get("municipality") or "0")
        postal_groups.setdefault(postal, []).append(idx)

    # 3. Spatial density clustering within each municipal/postal partition
    raw_clusters: List[List[int]] = []

    for postal, indices in postal_groups.items():
        if len(indices) < min_houses:
            continue

        pts = [Point(coords_arr[i, 0], coords_arr[i, 1]) for i in indices]
        tree = STRtree(pts)
        pairs = tree.query(pts, predicate="dwithin", distance=eps_m)

        # Disjoint-Set Union-Find
        parent = np.arange(len(indices))

        def find(u: int) -> int:
            path = []
            while parent[u] != u:
                path.append(u)
                u = parent[u]
            for node in path:
                parent[node] = u
            return u

        def union(u: int, v: int) -> None:
            ru = find(u)
            rv = find(v)
            if ru != rv:
                parent[ru] = rv

        for a, b in zip(pairs[0], pairs[1]):
            union(int(a), int(b))

        components: Dict[int, List[int]] = {}
        for local_idx in range(len(indices)):
            root = find(local_idx)
            components.setdefault(root, []).append(indices[local_idx])

        for comp_indices in components.values():
            if len(comp_indices) >= min_houses:
                # Subdivide mega-clusters if necessary
                if len(comp_indices) > max_houses:
                    sub_clusters = subdivide_large_cluster(comp_indices, coords_arr, max_size=max_houses)
                    for sc in sub_clusters:
                        if len(sc) >= min_houses:
                            raw_clusters.append(sc)
                else:
                    raw_clusters.append(comp_indices)

    logger.info("Discovered %d raw neighborhood clusters. Building boundary geometries...", len(raw_clusters))

    # 4. Generate boundary geometries and compute rich properties
    features: List[Dict[str, Any]] = []

    for cluster_idx, c_indices in enumerate(raw_clusters, start=1):
        c_houses = [cleaned_houses[i] for i in c_indices]
        count = len(c_houses)

        # Spatial Centroid & Viewpoint
        c_lats = [float(h["lat"]) for h in c_houses if h.get("lat") is not None]
        c_lons = [float(h["lon"]) for h in c_houses if h.get("lon") is not None]
        centroid_lat = round(float(np.mean(c_lats)), 6) if c_lats else 0.0
        centroid_lon = round(float(np.mean(c_lons)), 6) if c_lons else 0.0

        # Viewpoint (house closest to centroid for authentic Street View drop)
        center_pt = Point(np.mean(coords_arr[c_indices, 0]), np.mean(coords_arr[c_indices, 1]))
        distances = [center_pt.distance(Point(coords_arr[i, 0], coords_arr[i, 1])) for i in c_indices]
        closest_idx = c_indices[int(np.argmin(distances))]
        view_lat = cleaned_houses[closest_idx].get("lat", centroid_lat)
        view_lon = cleaned_houses[closest_idx].get("lon", centroid_lon)

        # Boundary Polygon via Concave Hull
        pts = [Point(coords_arr[i, 0], coords_arr[i, 1]) for i in c_indices]
        mp = MultiPoint(pts)

        try:
            if len(pts) >= 4:
                hull = concave_hull(mp, ratio=concave_ratio)
                poly = hull.buffer(buffer_m).simplify(2.0)
            else:
                poly = mp.convex_hull.buffer(buffer_m).simplify(2.0)
        except Exception:
            poly = mp.convex_hull.buffer(buffer_m).simplify(2.0)

        # Extract Polygon rings
        if poly.geom_type == "Polygon":
            polys = [poly]
        elif poly.geom_type == "MultiPolygon":
            polys = list(poly.geoms)
        else:
            polys = [poly.convex_hull]

        # Convert exterior LV95 coordinates to WGS84 [lon, lat]
        geojson_coords: List[List[List[float]]] = []
        for p in polys:
            if not hasattr(p, "exterior") or p.exterior is None:
                continue
            ring = []
            for e, n in p.exterior.coords:
                w_lat, w_lon = lv95_to_wgs84(e, n)
                ring.append([round(w_lon, 6), round(w_lat, 6)])
            if ring:
                geojson_coords.append(ring)

        if not geojson_coords:
            continue

        geom_doc = {
            "type": "Polygon" if len(geojson_coords) == 1 else "MultiPolygon",
            "coordinates": geojson_coords if len(geojson_coords) == 1 else [[r] for r in geojson_coords],
        }

        # Locality & Labeling
        postals = Counter(str(h.get("postal_code") or "") for h in c_houses if h.get("postal_code"))
        dominant_postal = postals.most_common(1)[0][0] if postals else ""
        cities = Counter(str(h.get("city") or h.get("municipality") or "") for h in c_houses if h.get("city") or h.get("municipality"))
        dominant_city = cities.most_common(1)[0][0] if cities else "Schweiz"
        cantons = Counter(str(h.get("canton") or "") for h in c_houses if h.get("canton"))
        dominant_canton = cantons.most_common(1)[0][0] if cantons else ""
        
        street_counts = Counter(str(h.get("street") or "") for h in c_houses if h.get("street"))
        top_streets = [s for s, _ in street_counts.most_common(4) if s and s.strip()]
        street_str = ", ".join(top_streets[:3]) if top_streets else "Residential Quarter"

        neighborhood_id = f"nb_{dominant_postal}_{cluster_idx}"
        label = f"{dominant_postal} {dominant_city} ({dominant_canton}) - {street_str}"

        # Metrics aggregation
        gardens = [float(h["estimated_garden_m2"]) for h in c_houses if h.get("estimated_garden_m2") is not None]
        greens = [float(h["green_ratio"]) for h in c_houses if h.get("green_ratio") is not None]
        prices_m2 = [float(h["median_price_per_m2"]) for h in c_houses if h.get("median_price_per_m2") is not None]
        house_prices = [float(h["estimated_price_chf"]) for h in c_houses if h.get("estimated_price_chf") is not None]
        bldg_areas = [float(h["building_area_m2"]) for h in c_houses if h.get("building_area_m2") is not None]
        
        target_cities = Counter(str(h.get("nearest_big_city") or "") for h in c_houses if h.get("nearest_big_city"))
        dominant_big_city = target_cities.most_common(1)[0][0] if target_cities else "City"
        commutes = [float(h["transit_travel_time_min"]) for h in c_houses if h.get("transit_travel_time_min") is not None]
        cadences = [float(h["transit_cadence_min"]) for h in c_houses if h.get("transit_cadence_min") is not None]
        total_commutes = [float(h["total_commute_min"]) for h in c_houses if h.get("total_commute_min") is not None]
        hops_list = [int(h["transit_hops"]) for h in c_houses if h.get("transit_hops") is not None]
        routes = Counter(str(h.get("transit_route_desc") or "") for h in c_houses if h.get("transit_route_desc"))
        dominant_route = routes.most_common(1)[0][0] if routes else "Direct train (0 transfers)"

        walk_transits = [float(h["walk_time_transit_min"]) for h in c_houses if h.get("walk_time_transit_min") is not None]
        walk_rests = [float(h["walk_time_restaurant_min"]) for h in c_houses if h.get("walk_time_restaurant_min") is not None]
        num_restos = [int(h["num_restaurants_nearby"]) for h in c_houses if h.get("num_restaurants_nearby") is not None]
        num_cafes = [int(h["num_cafes_nearby"]) for h in c_houses if h.get("num_cafes_nearby") is not None]
        walk_sms = [float(h["walk_time_supermarket_min"]) for h in c_houses if h.get("walk_time_supermarket_min") is not None]
        sm_brands = Counter(str(h.get("supermarket_brand") or "") for h in c_houses if h.get("supermarket_brand"))
        dominant_sm = sm_brands.most_common(1)[0][0] if sm_brands else "Supermarket"

        walk_gyms = [float(h["walk_time_gym_min"]) for h in c_houses if h.get("walk_time_gym_min") is not None]
        gym_names = Counter(str(h.get("nearest_gym") or "") for h in c_houses if h.get("nearest_gym"))
        dominant_gym = gym_names.most_common(1)[0][0] if gym_names else "Fitnesscenter"

        # Schools & Daycares
        walk_schools = [float(h["walk_time_school_min"]) for h in c_houses if h.get("walk_time_school_min") is not None]
        school_names = Counter(str(h.get("nearest_school") or "") for h in c_houses if h.get("nearest_school"))
        dominant_school = school_names.most_common(1)[0][0] if school_names else "Primary School"
        dist_schools = [float(h["dist_to_school_m"]) for h in c_houses if h.get("dist_to_school_m") is not None]

        walk_daycares = [float(h["walk_time_daycare_min"]) for h in c_houses if h.get("walk_time_daycare_min") is not None]
        access_daycares = [float(h["daycare_access_min"]) for h in c_houses if h.get("daycare_access_min") is not None]
        daycare_names = Counter(str(h.get("nearest_daycare") or "") for h in c_houses if h.get("nearest_daycare"))
        dominant_daycare = daycare_names.most_common(1)[0][0] if daycare_names else "Daycare / Crèche"
        daycare_modes = Counter(str(h.get("daycare_access_mode") or "walk") for h in c_houses if h.get("daycare_access_mode"))
        dominant_dc_mode = daycare_modes.most_common(1)[0][0] if daycare_modes else "walk"
        dist_daycares = [float(h["dist_to_daycare_m"]) for h in c_houses if h.get("dist_to_daycare_m") is not None]

        # Quietness vs Road Safety
        quietness = [float(h["quietness_score"]) for h in c_houses if h.get("quietness_score") is not None]
        road_safeties = [float(h["road_safety_score"]) for h in c_houses if h.get("road_safety_score") is not None]
        dist_main_roads = [float(h["dist_to_main_road_m"]) for h in c_houses if h.get("dist_to_main_road_m") is not None]
        calm_lanes = sum(1 for h in c_houses if h.get("street_typology") == "calm_lane")

        # Natural Hazards
        hazard_free_cnt = sum(1 for h in c_houses if not h.get("in_hazard_zone"))
        hazard_free = (hazard_free_cnt == count)

        # Microclimate & Solar Aspect
        sun_scores = [float(h["sun_exposure_score"]) for h in c_houses if h.get("sun_exposure_score") is not None]
        aspects = Counter(str(h.get("slope_aspect") or "") for h in c_houses if h.get("slope_aspect"))
        dominant_aspect = aspects.most_common(1)[0][0] if aspects else "South-West (Open Plateau)"
        aspect_degs = [float(h["slope_aspect_deg"]) for h in c_houses if h.get("slope_aspect_deg") is not None]
        south_facing_cnt = sum(1 for h in c_houses if h.get("is_south_facing"))
        is_south_facing = (south_facing_cnt / max(count, 1)) >= 0.5

        # Municipal Taxes
        taxes = [float(h["tax_multiplier_pct"]) for h in c_houses if h.get("tax_multiplier_pct") is not None]
        tax_tiers = Counter(str(h.get("tax_tier") or "") for h in c_houses if h.get("tax_tier"))
        dominant_tax_tier = tax_tiers.most_common(1)[0][0] if tax_tiers else "Moderate"

        # Viewsheds
        lake_houses = [h for h in c_houses if h.get("has_lake_view")]
        lake_view_ratio = round(len(lake_houses) / count, 2)
        dominant_lake = Counter(str(h.get("visible_lake") or "") for h in lake_houses if h.get("visible_lake")).most_common(1)
        dom_lake_name = dominant_lake[0][0] if dominant_lake else "None"
        lake_summary = f"{dom_lake_name} ({int(lake_view_ratio*100)}%)" if lake_view_ratio >= 0.20 and dom_lake_name != "None" else ("None" if lake_view_ratio < 0.20 else f"{dom_lake_name}")

        mtn_houses = [h for h in c_houses if h.get("has_mountain_view")]
        mountain_view_ratio = round(len(mtn_houses) / count, 2)
        dominant_peaks = Counter(str(h.get("visible_peaks") or "") for h in mtn_houses if h.get("visible_peaks")).most_common(1)
        dom_peaks_str = dominant_peaks[0][0] if dominant_peaks else "None"
        mtn_summary = f"{dom_peaks_str} ({int(mountain_view_ratio*100)}%)" if mountain_view_ratio >= 0.20 and dom_peaks_str != "None" else ("None" if mountain_view_ratio < 0.20 else f"{dom_peaks_str}")

        # Airports
        dominant_airport = Counter(str(h.get("nearest_airport") or "") for h in c_houses if h.get("nearest_airport")).most_common(1)
        dom_airport_name = dominant_airport[0][0] if dominant_airport else "None"
        dist_airports = [float(h["dist_to_airport_km"]) for h in c_houses if h.get("dist_to_airport_km") is not None]
        med_dist_airport = compute_median(dist_airports, default=15.0)
        airport_summary = f"{dom_airport_name} ({med_dist_airport:.1f} km)" if dom_airport_name != "None" else "None"

        # Dominant house type
        type_counts = Counter(str(h.get("building_type") or "house") for h in c_houses)
        dominant_type = type_counts.most_common(1)[0][0]

        # Street View link
        street_view_url = format_street_view_url(view_lat, view_lon)
        google_street_view = format_street_view_html(view_lat, view_lon)

        props: Dict[str, Any] = {
            "neighborhood_id": neighborhood_id,
            "neighborhood_label": label,
            "house_count": count,
            "dominant_house_type": dominant_type,
            "top_streets": top_streets,
            "postal_code": dominant_postal,
            "city": dominant_city,
            "canton": dominant_canton,
            "centroid_lat": centroid_lat,
            "centroid_lon": centroid_lon,
            "viewpoint_lat": round(float(view_lat), 6),
            "viewpoint_lon": round(float(view_lon), 6),
            "street_view_url": street_view_url,
            "google_street_view": google_street_view,
            "nearest_big_city": dominant_big_city,
            "median_commute_min": compute_median(commutes, default=15.0),
            "median_transit_cadence_min": compute_median(cadences, default=15.0),
            "median_total_commute_min": compute_median(total_commutes, default=20.0),
            "median_transit_hops": compute_median(hops_list, default=1),
            "dominant_transit_route": dominant_route,
            "median_garden_m2": compute_median(gardens, default=250.0),
            "median_green_ratio": compute_median(greens, default=0.55),
            "median_building_m2": compute_median(bldg_areas, default=70.0),
            "median_price_per_m2": compute_median(prices_m2, default=9500.0),
            "median_house_price_chf": compute_median(house_prices, default=1450000.0),
            "median_walk_transit_min": compute_median(walk_transits, default=4.0),
            "median_walk_restaurant_min": compute_median(walk_rests, default=5.0),
            "median_restaurants_nearby": int(compute_median(num_restos, default=3)),
            "median_cafes_nearby": int(compute_median(num_cafes, default=1)),
            "median_walk_supermarket_min": compute_median(walk_sms, default=6.0),
            "dominant_supermarket": dominant_sm,
            "median_walk_gym_min": compute_median(walk_gyms, default=10.0),
            "dominant_gym": dominant_gym,
            "median_quietness_score": compute_median(quietness, default=85.0),
            "median_road_safety_score": compute_median(road_safeties, default=80.0),
            "median_dist_main_road_m": compute_median(dist_main_roads, default=100.0),
            "calm_lanes_ratio": round(calm_lanes / max(count, 1), 2),
            "hazard_free": hazard_free,
            "hazard_status": "✅ Hazard-Free Zone" if hazard_free else "⚠️ Hazard Zone",
            "median_walk_school_min": compute_median(walk_schools, default=8.0),
            "dominant_school": dominant_school,
            "median_dist_school_m": compute_median(dist_schools, default=640.0),
            "median_walk_daycare_min": compute_median(walk_daycares, default=8.0),
            "median_daycare_access_min": compute_median(access_daycares, default=8.0),
            "dominant_daycare_mode": dominant_dc_mode,
            "dominant_daycare": dominant_daycare,
            "median_dist_daycare_m": compute_median(dist_daycares, default=640.0),
            "median_sun_exposure_score": compute_median(sun_scores, default=75.0),
            "dominant_slope_aspect": dominant_aspect,
            "median_slope_aspect_deg": compute_median(aspect_degs, default=180.0),
            "is_south_facing": is_south_facing,
            "tax_multiplier_pct": compute_median(taxes, default=65.0),
            "tax_tier": dominant_tax_tier,
            "tax_summary": f"{compute_median(taxes, default=65.0):.1f}% ({dominant_tax_tier})",
            "has_lake_view": lake_view_ratio >= 0.20,
            "lake_view_ratio": lake_view_ratio,
            "visible_lake": dom_lake_name,
            "lake_view_summary": lake_summary,
            "has_mountain_view": mountain_view_ratio >= 0.20,
            "mountain_view_ratio": mountain_view_ratio,
            "visible_peaks": dom_peaks_str,
            "mountain_view_summary": mtn_summary,
            "nearest_airport": dom_airport_name,
            "median_dist_airport_km": med_dist_airport,
            "airport_summary": airport_summary,
        }

        # Calculate composite Livability & Garden Index
        props["livability_score"] = calculate_livability_score(props)

        features.append({
            "type": "Feature",
            "geometry": geom_doc,
            "properties": props,
        })

    # Sort descending by livability score
    features.sort(key=lambda x: x["properties"]["livability_score"], reverse=True)
    logger.info("Successfully assembled %d discovered neighborhood polygons!", len(features))
    return features


def export_neighborhoods(
    neighborhood_features: List[Dict[str, Any]],
    output_dir: Path | str = "output",
) -> Dict[str, Path]:
    """Export discovered neighborhoods to GeoJSON and Parquet formats."""
    out_path = Path(output_dir)
    out_path.mkdir(parents=True, exist_ok=True)
    generated: Dict[str, Path] = {}

    # 1. GeoJSON Export
    geojson_path = out_path / "neighborhoods.geojson"
    geojson_doc = {
        "type": "FeatureCollection",
        "name": "discovered_neighborhoods",
        "features": neighborhood_features,
    }
    with open(geojson_path, "w", encoding="utf-8") as f:
        json.dump(geojson_doc, f, indent=2)
    logger.info("Saved neighborhoods GeoJSON: %s (%d neighborhoods)", geojson_path, len(neighborhood_features))
    generated["geojson"] = geojson_path

    # 2. Parquet Export via PyArrow
    parquet_path = out_path / "neighborhoods.parquet"
    if neighborhood_features:
        import pyarrow as pa
        import pyarrow.parquet as pq

        flat_records = []
        for feat in neighborhood_features:
            rec = dict(feat["properties"])
            # Format top_streets as comma-separated string for tabular storage
            if isinstance(rec.get("top_streets"), list):
                rec["top_streets"] = ", ".join(rec["top_streets"])
            flat_records.append(rec)

        table = pa.Table.from_pylist(flat_records)
        pq.write_table(table, str(parquet_path), compression="zstd")
        logger.info("Saved neighborhoods Parquet: %s", parquet_path)
        generated["parquet"] = parquet_path

    return generated
