"""Command-line interface (Typer) for the Swiss Housing Discovery geospatial pipeline.

Subcommands:
- fetch: Download official Swiss OGD bulk datasets into data/raw/
- build: Ingest raw datasets into local DuckDB with spatial tables
- query: Execute offline filtering, hybrid garden scoring, and export matching houses
- map: Aggregate matching houses into H3 hexes and export interactive HTML density map
- run: End-to-end query and map generation
"""

from __future__ import annotations

import json
import logging
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional

import typer
from rich.console import Console
from rich.logging import RichHandler
from rich.table import Table

from ch_housing.density import (
    build_interactive_density_map,
    detect_garden_enclaves,
    generate_density_layers,
    load_matching_houses_geojson,
)
from ch_housing.download import fetch_all, fetch_dataset, load_config
from ch_housing.ingest import build_database
from ch_housing.neighborhoods import discover_neighborhoods
from ch_housing.pipeline import HousingFilterCriteria, run_pipeline
from ch_housing.seed import seed_sample_database

app = typer.Typer(
    name="ch-housing",
    help="Offline-first geospatial pipeline to locate Swiss private houses with gardens.",
    add_completion=False,
)
console = Console()


def setup_logging(verbose: bool = False) -> None:
    """Configure rich logging format."""
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format="%(message)s",
        datefmt="[%X]",
        handlers=[RichHandler(console=console, rich_tracebacks=True, show_path=False)],
    )


@app.command()
def fetch(
    dataset: Optional[str] = typer.Option(
        None, "--dataset", "-d", help="Specific dataset key to fetch (gwr, transit, statpop, bauzonen, land_cover). Default: all"
    ),
    force: bool = typer.Option(False, "--force", "-f", help="Force redownload even if file is cached"),
    dynamic_stac: bool = typer.Option(True, "--stac/--no-stac", help="Query STAC API for newest release assets"),
    config_path: Path = typer.Option("config.default.yaml", "--config", "-c", help="Path to config YAML"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose debug logging"),
) -> None:
    """Download official Swiss Open Government Data bulk releases into data/raw/."""
    setup_logging(verbose)
    cfg = load_config(config_path)

    console.print("[bold green]Starting Swiss Open Government Data download...[/bold green]")
    if dataset:
        path = fetch_dataset(dataset, cfg, force=force, dynamic_stac=dynamic_stac)
        console.print(f"[green]Successfully fetched {dataset}:[/green] {path}")
    else:
        results = fetch_all(cfg, force=force, dynamic_stac=dynamic_stac)
        console.print("[bold green]All datasets successfully fetched:[/bold green]")
        for k, p in results.items():
            console.print(f" • [cyan]{k}[/cyan] -> {p}")


@app.command()
def build(
    config_path: Path = typer.Option("config.default.yaml", "--config", "-c", help="Path to config YAML"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose debug logging"),
) -> None:
    """Ingest raw downloaded datasets into local DuckDB database (data/processed/switzerland.duckdb)."""
    setup_logging(verbose)
    cfg = load_config(config_path)
    console.print("[bold blue]Ingesting raw datasets into DuckDB Spatial...[/bold blue]")
    build_database(cfg)
    console.print("[bold green]DuckDB spatial database ready for offline queries![/bold green]")


@app.command()
def seed(
    config_path: Path = typer.Option("config.default.yaml", "--config", "-c", help="Path to config YAML"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose debug logging"),
) -> None:
    """Populate DuckDB with realistic Swiss sample records across cantons for instant offline demo/testing."""
    setup_logging(verbose)
    cfg = load_config(config_path)
    storage = cfg.get("storage", {})
    db_path = storage.get("db_path", "data/processed/switzerland.duckdb")
    count = seed_sample_database(db_path)
    console.print(f"[bold green]Seeded {count} sample buildings into {db_path}![/bold green]")
    console.print("You can now immediately run [cyan]ch-housing query[/cyan] and [cyan]ch-housing map[/cyan]!")


@app.command()
def query(
    cantons: Optional[str] = typer.Option(
        None, "--cantons", help="Comma-separated 2-letter canton codes (e.g. ZH,BE,AG). Default: ALL"
    ),
    building_type: Optional[str] = typer.Option(
        None, "--building-type", help="Classification: 'house' (default: standalone, dual-family, row), 'standalone', 'dual-family', 'row', 'small-mfh', or 'any'"
    ),
    max_units: Optional[int] = typer.Option(
        None, "--max-units", help="Maximum dwellings per building (default 2 to include dual-family and single-family/row)"
    ),
    include_mixed_use: bool = typer.Option(
        False, "--include-mixed-use/--pure-residential-only", help="Include GKAT 1030 (minor secondary use) or pure residential GKAT 1020 only"
    ),
    transit_classes: Optional[str] = typer.Option(
        None, "--transit-classes", help="Allowed ARE ÖV-Güteklassen (comma-separated e.g. A,B,C). Default: A,B,C"
    ),
    max_transit_walk_min: Optional[float] = typer.Option(
        None, "--max-transit-walk-min", help="Maximum walking time to public transit in minutes (default 10.0)"
    ),
    max_transit_dist_m: Optional[float] = typer.Option(
        None, "--max-transit-dist-m", help="Maximum walking distance to public transit in meters (default 800.0)"
    ),
    max_restaurant_walk_min: Optional[float] = typer.Option(
        None, "--max-restaurant-walk-min", help="Maximum walking time to nearest restaurant in minutes (default 10.0)"
    ),
    max_restaurant_dist_m: Optional[float] = typer.Option(
        None, "--max-restaurant-dist-m", help="Maximum walking distance to nearest restaurant in meters (default 800.0)"
    ),
    min_restaurants: Optional[int] = typer.Option(
        None, "--min-restaurants", "--min-restaurants-nearby", help="Minimum number of restaurants/takeaways within 10 min walk (800m)"
    ),
    min_cafes: Optional[int] = typer.Option(
        None, "--min-cafes", "--min-cafes-nearby", help="Minimum number of cafés within 10 min walk (800m)"
    ),
    max_supermarket: Optional[float] = typer.Option(
        None, "--max-supermarket", "--max-supermarket-walk-min", help="Maximum walking time to a genuine supermarket in minutes (default 10.0)"
    ),
    max_supermarket_dist_m: Optional[float] = typer.Option(
        None, "--max-supermarket-dist-m", help="Maximum walking distance to a genuine supermarket in meters (default 800.0)"
    ),
    max_gym: Optional[float] = typer.Option(
        None, "--max-gym", "--max-gym-walk-min", help="Maximum walking time to a gym / fitness center in minutes (default 20.0)"
    ),
    max_gym_dist_m: Optional[float] = typer.Option(
        None, "--max-gym-dist-m", help="Maximum walking distance to a gym in meters (default 1600.0)"
    ),
    max_school_walk_min: Optional[float] = typer.Option(
        None, "--max-school-walk-min", "--max-school", help="Maximum walking time to primary school in minutes"
    ),
    max_school_dist_m: Optional[float] = typer.Option(
        None, "--max-school-dist-m", help="Maximum walking distance to primary school in meters"
    ),
    max_daycare_walk_min: Optional[float] = typer.Option(
        None, "--max-daycare-walk-min", "--max-daycare", help="Maximum walking time to daycare / crèche in minutes"
    ),
    max_daycare_access_min: Optional[float] = typer.Option(
        None, "--max-daycare-access-min", "--max-daycare-access", help="Maximum door-to-door access time (walk or transit) to daycare in minutes"
    ),
    max_daycare_dist_m: Optional[float] = typer.Option(
        None, "--max-daycare-dist-m", help="Maximum walking distance to daycare in meters"
    ),
    min_road_safety_score: Optional[float] = typer.Option(
        None, "--min-road-safety-score", "--min-road-safety", help="Minimum road safety score 0-100"
    ),
    min_dist_to_main_road_m: Optional[float] = typer.Option(
        None, "--min-dist-to-main-road-m", help="Minimum setback distance from main/arterial roads in meters"
    ),
    exclude_natural_hazards: bool = typer.Option(
        True, "--exclude-natural-hazards/--allow-natural-hazards", "--exclude-hazards/--allow-hazards", help="Strictly eliminate properties intersecting official natural hazard zones (flood, avalanche, etc.)"
    ),
    require_south_facing: bool = typer.Option(
        False, "--require-south-facing/--any-slope-aspect", "--south-facing/--any-slope", help="Require South / South-West facing slope aspect (Südhang)"
    ),
    min_sun_exposure_score: Optional[float] = typer.Option(
        None, "--min-sun-exposure-score", "--min-sun-score", help="Minimum solar exposure score 0-100"
    ),
    max_tax_multiplier_pct: Optional[float] = typer.Option(
        None, "--max-tax-multiplier-pct", "--max-tax", help="Maximum municipal tax multiplier percentage (Steuerfuss / Coefficient d'impôt, e.g. 70.0)"
    ),
    min_density: Optional[float] = typer.Option(
        None, "--min-density", help="Minimum local population density (residents / hectare)"
    ),
    max_density: Optional[float] = typer.Option(
        None, "--max-density", help="Maximum local population density (residents / hectare)"
    ),
    min_garden_m2: Optional[float] = typer.Option(
        None, "--min-garden-m2", help="Minimum estimated private garden area in square meters (default 100)"
    ),
    min_green_ratio: Optional[float] = typer.Option(
        None, "--min-green-ratio", help="Minimum green surface ratio in building buffer 0.0-1.0 (default 0.35)"
    ),
    garden_buffer_m: Optional[float] = typer.Option(
        None, "--garden-buffer-m", help="Radius in meters for building parcel proxy buffer (default 20)"
    ),
    exclude_arterial: bool = typer.Option(
        True, "--exclude-arterial/--include-arterial", help="Exclude houses on major arterial thoroughfares (Hauptstrasse, etc.)"
    ),
    min_motorway_dist_m: Optional[float] = typer.Option(
        None, "--min-motorway-dist-m", help="Minimum distance from motorway corridors in meters (default 200)"
    ),
    min_railway_dist_m: Optional[float] = typer.Option(
        None, "--min-railway-dist-m", help="Minimum distance from heavy railway tracks in meters (default 100)"
    ),
    min_quietness_score: Optional[float] = typer.Option(
        None, "--min-quietness-score", help="Minimum acoustic quietness score 0-100 (default 65)"
    ),
    calm_lanes_only: bool = typer.Option(
        False, "--calm-lanes-only", help="Keep strictly pedestrian lanes, ways, and cul-de-sacs (-weg, -gasse, -hof, chemin, etc.)"
    ),
    max_price_chf: Optional[float] = typer.Option(
        None, "--max-price-chf", "--max-price", help="Maximum estimated house price in CHF (e.g. 3000000.0)"
    ),
    max_price_per_m2: Optional[float] = typer.Option(
        None, "--max-price-m2", help="Maximum median price per square meter in CHF (e.g. 15000.0)"
    ),
    max_commute: Optional[float] = typer.Option(
        None, "--max-commute", "--max-commute-min", help="Maximum transit commute time to a big city in minutes (default 25.0)"
    ),
    max_cadence: Optional[float] = typer.Option(
        None, "--max-cadence", "--max-cadence-min", help="Maximum daytime transit service headway in minutes (default 15.0 / Viertelstundentakt)"
    ),
    max_hops: Optional[int] = typer.Option(
        None, "--max-hops", "--max-transit-hops", help="Maximum transit transfers/hops to big city (default 1: max 1 bus + 1 train; 0: direct only)"
    ),
    commute_city: Optional[str] = typer.Option(
        None, "--commute-city", help="Target big city name for commute (e.g. Zürich, Basel, Bern, Genève, Lausanne)"
    ),
    lake_view: Optional[bool] = typer.Option(
        None, "--lake-view/--no-lake-view", help="Filter for houses with unobstructed lake view (Seesicht)"
    ),
    min_lake_view_pct: Optional[float] = typer.Option(
        None, "--min-lake-view-pct", help="Minimum lake viewshed visibility percentage 0-100 (default 15.0)"
    ),
    mountain_view: Optional[bool] = typer.Option(
        None, "--mountain-view/--no-mountain-view", help="Filter for houses with Alpine mountain panorama"
    ),
    min_mountain_view_score: Optional[float] = typer.Option(
        None, "--min-mountain-view-score", help="Minimum Alpine panorama viewshed score 0-100 (default 25.0)"
    ),
    min_airport_dist_km: Optional[float] = typer.Option(
        None, "--min-airport-dist-km", help="Minimum distance from major Swiss airports in km (default 5.0 for ZRH, GVA, BSL)"
    ),
    min_regional_airport_dist_km: Optional[float] = typer.Option(
        None, "--min-regional-airport-dist-km", help="Minimum distance from regional/military airfields in km (default 2.5)"
    ),
    no_airport_filter: bool = typer.Option(
        False, "--no-airport-filter", help="Disable airport distance filtering completely"
    ),
    config_path: Path = typer.Option("config.default.yaml", "--config", "-c", help="Path to config YAML"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose debug logging"),
) -> None:
    """Execute offline spatial filtering and export matching houses to GeoParquet and GeoJSON."""
    setup_logging(verbose)
    cfg = load_config(config_path)

    overrides = {
        "cantons": cantons,
        "building_type": building_type,
        "max_units": max_units,
        "include_mixed_use": include_mixed_use,
        "transit_classes": transit_classes,
        "max_transit_walk_min": max_transit_walk_min,
        "max_transit_dist_m": max_transit_dist_m,
        "max_restaurant_walk_min": max_restaurant_walk_min,
        "max_restaurant_dist_m": max_restaurant_dist_m,
        "min_restaurants_nearby": min_restaurants,
        "min_cafes_nearby": min_cafes,
        "min_density": min_density,
        "max_density": max_density,
        "min_garden_m2": min_garden_m2,
        "min_green_ratio": min_green_ratio,
        "garden_buffer_m": garden_buffer_m,
        "exclude_arterial_streets": exclude_arterial,
        "min_motorway_dist_m": min_motorway_dist_m,
        "min_railway_dist_m": min_railway_dist_m,
        "min_quietness_score": min_quietness_score,
        "calm_lanes_only": calm_lanes_only,
        "max_price_chf": max_price_chf,
        "max_price_per_m2": max_price_per_m2,
        "max_commute_time_min": max_commute,
        "max_transit_cadence_min": max_cadence,
        "max_transit_hops": max_hops,
        "commute_target_city": commute_city,
        "max_supermarket_walk_min": max_supermarket,
        "max_supermarket_dist_m": max_supermarket_dist_m,
        "max_gym_walk_min": max_gym,
        "max_gym_dist_m": max_gym_dist_m,
        "max_school_walk_min": max_school_walk_min,
        "max_school_dist_m": max_school_dist_m,
        "max_daycare_walk_min": max_daycare_walk_min,
        "max_daycare_access_min": max_daycare_access_min,
        "max_daycare_dist_m": max_daycare_dist_m,
        "min_road_safety_score": min_road_safety_score,
        "min_dist_to_main_road_m": min_dist_to_main_road_m,
        "exclude_natural_hazards": exclude_natural_hazards,
        "require_south_facing": require_south_facing,
        "min_sun_exposure_score": min_sun_exposure_score,
        "max_tax_multiplier_pct": max_tax_multiplier_pct,
        "require_lake_view": lake_view,
        "min_lake_view_pct": min_lake_view_pct,
        "require_mountain_view": mountain_view,
        "min_mountain_view_score": min_mountain_view_score,
    }

    if no_airport_filter:
        overrides["min_airport_dist_km"] = None
        overrides["min_regional_airport_dist_km"] = None
    else:
        if min_airport_dist_km is not None:
            overrides["min_airport_dist_km"] = min_airport_dist_km
        if min_regional_airport_dist_km is not None:
            overrides["min_regional_airport_dist_km"] = min_regional_airport_dist_km

    console.print("[bold yellow]Executing offline spatial filtering & garden scoring...[/bold yellow]")
    count = run_pipeline(cfg, **overrides)
    console.print(f"[bold green]Successfully matched {count:,} houses![/bold green]")
    console.print("Outputs generated:")
    console.print(" • [cyan]output/matching_houses.parquet[/cyan]")
    console.print(" • [cyan]output/matching_houses.geojson[/cyan]")


@app.command()
def map(
    h3_res: int = typer.Option(7, "--h3-res", "-r", help="H3 hexagon resolution for spatial binning (default 7)"),
    input_geojson: Path = typer.Option(Path("output/matching_houses.geojson"), "--input", "-i", help="Path to matching_houses.geojson"),
    output_html: Path = typer.Option(Path("output/density_map.html"), "--output", "-o", help="Path for HTML map export"),
    basemap: str = typer.Option(
        "swisstopo-gray",
        "--basemap",
        "-b",
        help="Basemap layer (default: 'swisstopo-gray' / Official Federal OGD)",
    ),
    selector: bool = typer.Option(False, "--selector", help="Include layer selector control widget on the map (default: False)"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose debug logging"),
) -> None:
    """Aggregate matching houses into H3 hex density bins and generate interactive HTML map."""
    setup_logging(verbose)

    if not input_geojson.exists():
        console.print(f"[red]Error: Input file {input_geojson} does not exist. Run 'query' first![/red]")
        raise typer.Exit(code=1)

    houses = load_matching_houses_geojson(input_geojson)
    console.print(f"Loaded {len(houses):,} houses from {input_geojson}")

    # Generate density GeoJSON layers (resolutions 7, 8, and 9 + enclaves)
    generate_density_layers(houses, output_dir=output_html.parent, resolutions=[h3_res, 8, 9])

    # Generate self-contained interactive map with compliant OGD basemap
    html_path = build_interactive_density_map(
        houses,
        output_html_path=output_html,
        h3_resolution=h3_res,
        default_basemap=basemap,
        include_selector=selector,
    )
    console.print(f"[bold green]Interactive density map exported to:[/bold green] [cyan]{html_path}[/cyan]")


@app.command()
def neighborhoods(
    canton: Optional[str] = typer.Option(None, "--canton", "-c", help="Filter by canton e.g. ZH, BE, VD"),
    city: Optional[str] = typer.Option(None, "--city", help="Filter by city name e.g. Zürich, Bern"),
    postal: Optional[int] = typer.Option(None, "--postal", "-p", help="Filter by postal code e.g. 8700"),
    target_city: Optional[str] = typer.Option(None, "--target-city", "--commute-city", help="Filter by commute target city"),
    max_commute: Optional[float] = typer.Option(None, "--max-commute", help="Maximum commute time in minutes"),
    max_hops: Optional[int] = typer.Option(None, "--max-hops", help="Filter by maximum transit hops to big city (0 for direct, 1 for 1 transfer)"),
    max_price: Optional[float] = typer.Option(None, "--max-price", "--max-price-chf", help="Maximum median estimated house price in CHF"),
    max_price_m2: Optional[float] = typer.Option(None, "--max-price-m2", help="Maximum median price per m² in CHF"),
    min_garden: Optional[float] = typer.Option(None, "--min-garden", help="Minimum median garden area in m²"),
    lake_view: bool = typer.Option(False, "--lake-view", help="Filter for neighborhoods with lake view"),
    mountain_view: bool = typer.Option(False, "--mountain-view", help="Filter for neighborhoods with mountain view"),
    min_houses: int = typer.Option(15, "--min-houses", help="Minimum houses in neighborhood (default 15)"),
    sort_by: str = typer.Option("livability", "--sort-by", "-s", help="Sort by: 'livability' (default), 'houses', 'price', 'garden', 'commute'"),
    limit: int = typer.Option(25, "--limit", "-l", help="Number of neighborhoods to display (default 25)"),
    input_geojson: Path = typer.Option(Path("output/matching_houses.geojson"), "--input", "-i", help="Path to matching_houses.geojson"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose debug logging"),
) -> None:
    """Find, cluster, rank, and inspect contiguous residential neighborhoods."""
    setup_logging(verbose)

    nb_geojson = Path("output/neighborhoods.geojson")
    nb_list: List[Dict[str, Any]] = []

    if nb_geojson.exists():
        with open(nb_geojson, "r", encoding="utf-8") as f:
            nb_doc = json.load(f)
            nb_list = nb_doc.get("features", [])
    elif input_geojson.exists():
        houses = load_matching_houses_geojson(input_geojson)
        nb_list = discover_neighborhoods(houses, min_houses=min_houses)
    else:
        console.print(f"[red]Error: Neither {nb_geojson} nor {input_geojson} exists. Run 'query' first![/red]")
        raise typer.Exit(code=1)

    # Apply filters
    if canton:
        nb_list = [n for n in nb_list if str(n["properties"].get("canton", "")).upper() == canton.upper()]
    if postal:
        nb_list = [n for n in nb_list if int(n["properties"].get("postal_code", 0) or 0) == postal]
    if city:
        nb_list = [n for n in nb_list if city.lower() in str(n["properties"].get("city", "")).lower()]
    if target_city:
        nb_list = [n for n in nb_list if target_city.lower() in str(n["properties"].get("nearest_big_city", "")).lower()]
    if max_commute is not None:
        nb_list = [n for n in nb_list if n["properties"].get("median_commute_min", 999) <= max_commute]
    if max_hops is not None:
        nb_list = [n for n in nb_list if n["properties"].get("median_transit_hops", 1) <= max_hops]
    if max_price is not None:
        nb_list = [n for n in nb_list if n["properties"].get("median_house_price_chf", 0) <= max_price]
    if max_price_m2 is not None:
        nb_list = [n for n in nb_list if n["properties"].get("median_price_per_m2", 0) <= max_price_m2]
    if min_garden is not None:
        nb_list = [n for n in nb_list if n["properties"].get("median_garden_m2", 0) >= min_garden]
    if lake_view:
        nb_list = [n for n in nb_list if n["properties"].get("has_lake_view")]
    if mountain_view:
        nb_list = [n for n in nb_list if n["properties"].get("has_mountain_view")]
    if min_houses > 15:
        nb_list = [n for n in nb_list if n["properties"].get("house_count", 0) >= min_houses]

    # Sort
    if sort_by.lower() == "houses":
        nb_list.sort(key=lambda x: x["properties"].get("house_count", 0), reverse=True)
    elif sort_by.lower() == "price":
        nb_list.sort(key=lambda x: x["properties"].get("median_house_price_chf", 99999999))
    elif sort_by.lower() == "garden":
        nb_list.sort(key=lambda x: x["properties"].get("median_garden_m2", 0), reverse=True)
    elif sort_by.lower() == "commute":
        nb_list.sort(key=lambda x: x["properties"].get("median_commute_min", 999))
    else:  # default livability
        nb_list.sort(key=lambda x: (x["properties"].get("livability_score", 0), x["properties"].get("house_count", 0)), reverse=True)

    console.print(f"[bold green]Discovered {len(nb_list):,} residential neighborhoods:[/bold green]")

    table = Table(title=f"Discovered Residential Neighborhoods (Showing top {min(limit, len(nb_list))})")
    table.add_column("Neighborhood & Streets", style="cyan")
    table.add_column("Houses", justify="right", style="bold green")
    table.add_column("⭐ Score", justify="right", style="bold yellow")
    table.add_column("Median Garden", justify="right")
    table.add_column("Price / m²", justify="right", style="magenta")
    table.add_column("Est. Price", justify="right", style="bold green")
    table.add_column("City Commute", justify="right", style="yellow")
    table.add_column("Cadence", justify="right")
    table.add_column("Supermarket", justify="right", style="cyan")
    table.add_column("🌅 Lake", justify="right", style="cyan")
    table.add_column("🏔️ Mountain", justify="right", style="magenta")
    table.add_column("✈️ Airport", justify="right", style="cyan")
    table.add_column("Quietness", justify="right", style="green")
    table.add_column("Street View", style="blue")

    for nb in nb_list[:limit]:
        p = nb["properties"]
        streets = ", ".join(p.get("top_streets", [])[:3])
        loc = f"{p['postal_code']} {p['city']} ({p['canton']})"
        if streets:
            loc += f"\n[dim]{streets}[/dim]"
        q_score = int(p.get("median_quietness_score", 85))
        price_m2 = int(p.get("median_price_per_m2", 9500))
        house_price = float(p.get("median_house_price_chf", 1450000))
        price_color = "green" if house_price <= 3000000.0 else "red"
        commute_min = p.get("median_commute_min", 15.0)
        target = p.get("nearest_big_city", "City")
        cadence_min = p.get("median_transit_cadence_min", 15.0)
        sm_walk = p.get("median_walk_supermarket_min", 5.0)
        sm_brand = p.get("dominant_supermarket", "")
        sm_display = f"{sm_brand} ({sm_walk}m)" if sm_brand else f"{sm_walk}m"
        sv_url = p.get("street_view_url", "")
        sv_display = f"[link={sv_url}]Street View ↗[/link]" if sv_url else ""
        lake_disp = p.get("lake_view_summary", "None")
        lake_cell = f"[cyan]{lake_disp}[/cyan]" if lake_disp != "None" else "[dim]-[/dim]"
        mtn_disp = p.get("mountain_view_summary", "None")
        mtn_cell = f"[magenta]{mtn_disp}[/magenta]" if mtn_disp != "None" else "[dim]-[/dim]"
        apt_disp = p.get("airport_summary", "None")
        apt_cell = f"[cyan]{apt_disp}[/cyan]" if apt_disp != "None" else "[dim]-[/dim]"
        liv_score = p.get("livability_score", 0.0)

        table.add_row(
            loc,
            str(p["house_count"]),
            f"{liv_score:.1f}",
            f"{p['median_garden_m2']} m² ({int(p['median_green_ratio']*100)}%)",
            f"CHF {price_m2:,}",
            f"[{price_color}]CHF {house_price/1e6:.2f}M[/{price_color}]",
            f"{commute_min}m -> {target}",
            f"{cadence_min}m Takt",
            sm_display,
            lake_cell,
            mtn_cell,
            apt_cell,
            f"{q_score}/100",
            sv_display,
        )

    console.print(table)


@app.command()
def enclaves(
    canton: Optional[str] = typer.Option(None, "--canton", "-c", help="Filter by canton e.g. ZH"),
    postal: Optional[int] = typer.Option(None, "--postal", "-p", help="Filter by postal code e.g. 8048"),
    city: Optional[str] = typer.Option(None, "--city", help="Filter by city name e.g. Zürich"),
    min_houses: int = typer.Option(5, "--min-houses", help="Minimum houses in enclave (default 5)"),
    max_houses: int = typer.Option(100, "--max-houses", help="Maximum houses in enclave (default 100)"),
    calm_only: bool = typer.Option(False, "--calm-only", help="Keep strictly enclaves dominated by calm lanes/ways"),
    max_price: Optional[float] = typer.Option(None, "--max-price", "--max-price-chf", help="Maximum median house price in CHF (e.g. 3000000.0)"),
    max_commute: Optional[float] = typer.Option(None, "--max-commute", "--max-commute-min", help="Maximum commute time to big city in minutes (e.g. 25.0)"),
    max_hops: Optional[int] = typer.Option(None, "--max-hops", help="Filter enclaves by maximum transit hops to big city (0 for direct, 1 for 1 transfer)"),
    max_cadence: Optional[float] = typer.Option(None, "--max-cadence", "--max-cadence-min", help="Maximum daytime service headway in minutes (e.g. 15.0)"),
    commute_city: Optional[str] = typer.Option(None, "--commute-city", help="Filter enclaves by target big city (e.g. Zürich, Basel, Bern)"),
    max_supermarket: Optional[float] = typer.Option(None, "--max-supermarket", "--max-supermarket-walk-min", help="Filter enclaves by supermarket walking time in minutes (e.g. 10.0)"),
    lake_view: bool = typer.Option(False, "--lake-view", help="Keep only enclaves with lake view (Seesicht)"),
    min_lake_view_pct: Optional[float] = typer.Option(None, "--min-lake-view-pct", help="Minimum median lake view percentage (0-100)"),
    mountain_view: bool = typer.Option(False, "--mountain-view", help="Keep only enclaves with Alpine mountain panorama"),
    min_mountain_view_score: Optional[float] = typer.Option(None, "--min-mountain-view-score", help="Minimum median Alpine panorama score (0-100)"),
    min_airport_dist_km: Optional[float] = typer.Option(None, "--min-airport-dist-km", help="Filter enclaves by minimum distance to major airport in km"),
    limit: int = typer.Option(25, "--limit", "-l", help="Number of enclaves to display (default 25)"),
    input_geojson: Path = typer.Option(Path("output/matching_houses.geojson"), "--input", "-i", help="Path to matching_houses.geojson"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose debug logging"),
) -> None:
    """Find and rank intimate small patches / urban garden enclaves of private houses with gardens."""
    setup_logging(verbose)
    if not input_geojson.exists():
        console.print(f"[red]Error: Input file {input_geojson} does not exist. Run 'query' first![/red]")
        raise typer.Exit(code=1)

    houses = load_matching_houses_geojson(input_geojson)
    if canton:
        houses = [h for h in houses if str(h.get("canton", "")).upper() == canton.upper()]
    if postal:
        houses = [h for h in houses if int(h.get("postal_code", 0) or 0) == postal]
    if city:
        houses = [h for h in houses if city.lower() in str(h.get("city", "")).lower()]

    enclaves_list = detect_garden_enclaves(houses, min_houses=min_houses, max_houses=max_houses, resolution=9)
    if calm_only:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("calm_lanes_ratio", 0) >= 0.5]
    if max_price:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("median_house_price_chf", 0) <= max_price]
    if max_commute:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("median_commute_min", 999) <= max_commute]
    if max_hops is not None:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("median_transit_hops", 1) <= max_hops]
    if max_cadence:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("median_transit_cadence_min", 999) <= max_cadence]
    if commute_city:
        enclaves_list = [e for e in enclaves_list if commute_city.lower() in str(e["properties"].get("nearest_big_city", "")).lower()]
    if max_supermarket:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("median_walk_supermarket_min", 999) <= max_supermarket]
    if lake_view:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("has_lake_view")]
    if min_lake_view_pct is not None:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("median_lake_view_pct", 0) >= min_lake_view_pct]
    if mountain_view:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("has_mountain_view")]
    if min_mountain_view_score is not None:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("median_mountain_score", 0) >= min_mountain_view_score]
    if min_airport_dist_km is not None:
        enclaves_list = [e for e in enclaves_list if e["properties"].get("median_dist_airport_km", 0) >= min_airport_dist_km]

    enclaves_list.sort(key=lambda x: x["properties"]["house_count"], reverse=True)

    console.print(f"[bold green]Found {len(enclaves_list):,} garden enclaves ({min_houses}-{max_houses} houses):[/bold green]")

    table = Table(title=f"Urban Garden Enclaves (Showing top {min(limit, len(enclaves_list))})")
    table.add_column("Location & Streets", style="cyan")
    table.add_column("Houses", justify="right", style="bold green")
    table.add_column("Median Garden", justify="right")
    table.add_column("Price / m²", justify="right", style="magenta")
    table.add_column("Est. Price", justify="right", style="bold green")
    table.add_column("City Commute", justify="right", style="yellow")
    table.add_column("Cadence", justify="right")
    table.add_column("Stop Walk", justify="right")
    table.add_column("Resto Walk", justify="right")
    table.add_column("Supermarket", justify="right", style="cyan")
    table.add_column("🌅 Lake", justify="right", style="cyan")
    table.add_column("🏔️ Mountain", justify="right", style="magenta")
    table.add_column("✈️ Airport", justify="right", style="cyan")
    table.add_column("Quietness", justify="right", style="green")
    table.add_column("Street View", style="blue")
    table.add_column("Hex Cell", style="dim")

    for enc in enclaves_list[:limit]:
        p = enc["properties"]
        streets = ", ".join(p.get("top_streets", [])[:3])
        loc = f"{p['postal_code']} {p['city']}"
        if streets:
            loc += f"\n[dim]{streets}[/dim]"
        q_score = int(p.get("median_quietness_score", 95))
        price_m2 = int(p.get("median_price_per_m2", 8800))
        house_price = float(p.get("median_house_price_chf", 1350000))
        price_color = "green" if house_price <= 3000000.0 else "red"
        commute_min = p.get("median_commute_min", 15.0)
        target_city = p.get("nearest_big_city", "City")
        cadence_min = p.get("median_transit_cadence_min", 15.0)
        sm_walk = p.get("median_walk_supermarket_min", 5.0)
        sv_url = p.get("street_view_url", "")
        sv_display = f"[link={sv_url}]Street View ↗[/link]" if sv_url else ""
        lake_disp = p.get("lake_view_summary", "None")
        lake_cell = f"[cyan]{lake_disp}[/cyan]" if lake_disp != "None" else "[dim]-[/dim]"
        mtn_disp = p.get("mountain_view_summary", "None")
        mtn_cell = f"[magenta]{mtn_disp}[/magenta]" if mtn_disp != "None" else "[dim]-[/dim]"
        apt_disp = p.get("airport_summary", "None")
        apt_cell = f"[cyan]{apt_disp}[/cyan]" if apt_disp != "None" else "[dim]-[/dim]"
        table.add_row(
            loc,
            str(p["house_count"]),
            f"{p['median_garden_m2']} m² ({int(p['median_green_ratio']*100)}%)",
            f"CHF {price_m2:,}",
            f"[{price_color}]CHF {house_price/1e6:.2f}M[/{price_color}]",
            f"{commute_min}m -> {target_city}",
            f"{cadence_min}m Takt",
            f"{p['median_walk_transit_min']} min",
            f"{p['median_walk_restaurant_min']} min",
            f"{sm_walk} min",
            lake_cell,
            mtn_cell,
            apt_cell,
            f"{q_score}/100",
            sv_display,
            p["cell_id"],
        )

    console.print(table)


@app.command()
def run(
    cantons: Optional[str] = typer.Option(None, "--cantons", help="Comma-separated canton codes e.g. ZH,BE,AG"),
    building_type: Optional[str] = typer.Option(None, "--building-type", help="'house' (default: standalone, dual-family, row), 'small-mfh', or 'any'"),
    max_units: Optional[int] = typer.Option(None, "--max-units", help="Max dwellings per building (default 2)"),
    include_mixed_use: bool = typer.Option(False, "--include-mixed-use/--pure-residential-only"),
    transit_classes: Optional[str] = typer.Option(None, "--transit-classes", help="Allowed ÖV-Güteklassen (default A,B,C)"),
    max_transit_walk_min: Optional[float] = typer.Option(None, "--max-transit-walk-min", help="Max walk time to transit in minutes (default 10.0)"),
    max_transit_dist_m: Optional[float] = typer.Option(None, "--max-transit-dist-m", help="Max walk distance to transit in meters (default 800.0)"),
    max_restaurant_walk_min: Optional[float] = typer.Option(None, "--max-restaurant-walk-min", help="Max walk time to restaurant in minutes (default 10.0)"),
    max_restaurant_dist_m: Optional[float] = typer.Option(None, "--max-restaurant-dist-m", help="Max walk distance to restaurant in meters (default 800.0)"),
    min_restaurants: Optional[int] = typer.Option(None, "--min-restaurants", "--min-restaurants-nearby", help="Minimum number of restaurants/takeaways within 10 min walk (800m)"),
    min_cafes: Optional[int] = typer.Option(None, "--min-cafes", "--min-cafes-nearby", help="Minimum number of cafés within 10 min walk (800m)"),
    min_density: Optional[float] = typer.Option(None, "--min-density"),
    max_density: Optional[float] = typer.Option(None, "--max-density"),
    min_garden_m2: Optional[float] = typer.Option(None, "--min-garden-m2"),
    min_green_ratio: Optional[float] = typer.Option(None, "--min-green-ratio"),
    garden_buffer_m: Optional[float] = typer.Option(None, "--garden-buffer-m"),
    exclude_arterial: bool = typer.Option(True, "--exclude-arterial/--include-arterial"),
    min_motorway_dist_m: Optional[float] = typer.Option(None, "--min-motorway-dist-m"),
    min_railway_dist_m: Optional[float] = typer.Option(None, "--min-railway-dist-m"),
    min_quietness_score: Optional[float] = typer.Option(None, "--min-quietness-score"),
    calm_lanes_only: bool = typer.Option(False, "--calm-lanes-only"),
    max_price_chf: Optional[float] = typer.Option(None, "--max-price-chf", "--max-price"),
    max_price_per_m2: Optional[float] = typer.Option(None, "--max-price-m2"),
    max_commute: Optional[float] = typer.Option(None, "--max-commute", "--max-commute-min", help="Maximum transit commute to big city in minutes (default 25.0)"),
    max_cadence: Optional[float] = typer.Option(None, "--max-cadence", "--max-cadence-min", help="Maximum daytime transit service headway in minutes (default 15.0)"),
    max_hops: Optional[int] = typer.Option(None, "--max-hops", "--max-transit-hops", help="Maximum transit transfers/hops to big city (default 1: max 1 bus + 1 train; 0: direct only)"),
    commute_city: Optional[str] = typer.Option(None, "--commute-city", help="Target big city name for commute"),
    max_supermarket_walk_min: Optional[float] = typer.Option(None, "--max-supermarket-walk-min", help="Max walk time to supermarket in minutes (default 10.0)"),
    max_supermarket_dist_m: Optional[float] = typer.Option(None, "--max-supermarket-dist-m", help="Max walk distance to supermarket in meters (default 800.0)"),
    max_gym_walk_min: Optional[float] = typer.Option(None, "--max-gym-walk-min", "--max-gym", help="Max walk time to gym / sports facility in minutes (default 20.0)"),
    max_gym_dist_m: Optional[float] = typer.Option(None, "--max-gym-dist-m", help="Max walk distance to gym in meters (default 1600.0)"),
    max_school_walk_min: Optional[float] = typer.Option(None, "--max-school-walk-min", "--max-school", help="Max walk time to primary school in minutes"),
    max_school_dist_m: Optional[float] = typer.Option(None, "--max-school-dist-m", help="Max walk distance to primary school in meters"),
    max_daycare_walk_min: Optional[float] = typer.Option(None, "--max-daycare-walk-min", "--max-daycare", help="Max walk time to daycare in minutes"),
    max_daycare_access_min: Optional[float] = typer.Option(None, "--max-daycare-access-min", "--max-daycare-access", help="Max door-to-door access time (walk or transit) to daycare in minutes"),
    max_daycare_dist_m: Optional[float] = typer.Option(None, "--max-daycare-dist-m", help="Max walk distance to daycare in meters"),
    min_road_safety_score: Optional[float] = typer.Option(None, "--min-road-safety-score", "--min-road-safety", help="Minimum road safety score 0-100"),
    min_dist_to_main_road_m: Optional[float] = typer.Option(None, "--min-dist-to-main-road-m", help="Minimum distance from main roads in meters"),
    exclude_natural_hazards: bool = typer.Option(True, "--exclude-natural-hazards/--allow-natural-hazards", help="Exclude natural hazard zones"),
    require_south_facing: bool = typer.Option(False, "--require-south-facing/--any-slope-aspect", help="Require South-facing slope (Südhang)"),
    min_sun_exposure_score: Optional[float] = typer.Option(None, "--min-sun-exposure-score", "--min-sun-score", help="Minimum solar exposure score 0-100"),
    max_tax_multiplier_pct: Optional[float] = typer.Option(None, "--max-tax-multiplier-pct", "--max-tax", help="Maximum municipal tax multiplier percentage"),
    lake_view: Optional[bool] = typer.Option(None, "--lake-view/--no-lake-view", help="Filter for houses with unobstructed lake view"),
    min_lake_view_pct: Optional[float] = typer.Option(None, "--min-lake-view-pct", help="Minimum lake viewshed visibility percentage (default 15.0)"),
    mountain_view: Optional[bool] = typer.Option(None, "--mountain-view/--no-mountain-view", help="Filter for houses with Alpine mountain panorama"),
    min_mountain_view_score: Optional[float] = typer.Option(None, "--min-mountain-view-score", help="Minimum Alpine panorama viewshed score (default 25.0)"),
    min_airport_dist_km: Optional[float] = typer.Option(None, "--min-airport-dist-km", help="Minimum distance from major Swiss airports in km (default 5.0 for ZRH, GVA, BSL)"),
    min_regional_airport_dist_km: Optional[float] = typer.Option(None, "--min-regional-airport-dist-km", help="Minimum distance from regional/military airfields in km (default 2.5)"),
    no_airport_filter: bool = typer.Option(False, "--no-airport-filter", help="Disable airport distance filtering completely"),
    h3_res: int = typer.Option(7, "--h3-res", "-r", help="H3 hex resolution for density map"),
    basemap: str = typer.Option(
        "swisstopo-gray",
        "--basemap",
        "-b",
        help="Default basemap layer: 'swisstopo-gray' (default OGD), 'swisstopo-color', 'swisstopo-imagery', 'cartodb-positron', 'openstreetmap'",
    ),
    config_path: Path = typer.Option("config.default.yaml", "--config", "-c"),
    verbose: bool = typer.Option(False, "--verbose", "-v"),
) -> None:
    """Execute end-to-end filtering and interactive density map generation."""
    query(
        cantons=cantons,
        building_type=building_type,
        max_units=max_units,
        include_mixed_use=include_mixed_use,
        transit_classes=transit_classes,
        max_transit_walk_min=max_transit_walk_min,
        max_transit_dist_m=max_transit_dist_m,
        max_restaurant_walk_min=max_restaurant_walk_min,
        max_restaurant_dist_m=max_restaurant_dist_m,
        min_restaurants=min_restaurants,
        min_cafes=min_cafes,
        min_density=min_density,
        max_density=max_density,
        min_garden_m2=min_garden_m2,
        min_green_ratio=min_green_ratio,
        garden_buffer_m=garden_buffer_m,
        exclude_arterial=exclude_arterial,
        min_motorway_dist_m=min_motorway_dist_m,
        min_railway_dist_m=min_railway_dist_m,
        min_quietness_score=min_quietness_score,
        calm_lanes_only=calm_lanes_only,
        max_price_chf=max_price_chf,
        max_price_per_m2=max_price_per_m2,
        max_commute=max_commute,
        max_cadence=max_cadence,
        max_hops=max_hops,
        commute_city=commute_city,
        max_supermarket=max_supermarket_walk_min,
        max_supermarket_dist_m=max_supermarket_dist_m,
        max_gym=max_gym_walk_min,
        max_gym_dist_m=max_gym_dist_m,
        max_school_walk_min=max_school_walk_min,
        max_school_dist_m=max_school_dist_m,
        max_daycare_walk_min=max_daycare_walk_min,
        max_daycare_access_min=max_daycare_access_min,
        max_daycare_dist_m=max_daycare_dist_m,
        min_road_safety_score=min_road_safety_score,
        min_dist_to_main_road_m=min_dist_to_main_road_m,
        exclude_natural_hazards=exclude_natural_hazards,
        require_south_facing=require_south_facing,
        min_sun_exposure_score=min_sun_exposure_score,
        max_tax_multiplier_pct=max_tax_multiplier_pct,
        lake_view=lake_view,
        min_lake_view_pct=min_lake_view_pct,
        mountain_view=mountain_view,
        min_mountain_view_score=min_mountain_view_score,
        min_airport_dist_km=min_airport_dist_km,
        min_regional_airport_dist_km=min_regional_airport_dist_km,
        no_airport_filter=no_airport_filter,
        config_path=config_path,
        verbose=verbose,
    )
    map(
        h3_res=h3_res,
        input_geojson=Path("output/matching_houses.geojson"),
        output_html=Path("output/density_map.html"),
        basemap=basemap,
        verbose=verbose,
    )


if __name__ == "__main__":
    app()
