"""Download OpenStreetMap Gastronomy POIs for Switzerland with resilient tiling & caching.

Queries Overpass API in small spatial tiles (approx 16 tiles) to ensure fast,
reliable responses without timeouts. Caches each tile to disk immediately so
progress is never lost. Transforms WGS84 to Swiss LV95 (EPSG:2056) and exports
clean parquet and CSV to data/raw/restaurants/.
"""

from __future__ import annotations

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

import duckdb
import httpx
import pyarrow as pa
import pyarrow.parquet as pq

from ch_housing.viewshed import wgs84_to_lv95

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

CACHE_DIR = Path("data/raw/restaurants/cache")
OUT_DIR = Path("data/raw/restaurants")

OVERPASS_ENDPOINTS = [
    "https://overpass.osm.ch/api/interpreter",
    "https://lz4.overpass-api.de/api/interpreter",
    "https://overpass-api.de/api/interpreter",
]

# 26 Swiss Cantons ordered with major population centers first
SWISS_CANTONS = [
    "VD",  # Vaud (Pully, Lausanne, Montreux)
    "ZH",  # Zürich
    "GE",  # Genève
    "BE",  # Bern
    "BS",  # Basel-Stadt
    "BL",  # Basel-Landschaft
    "LU",  # Luzern
    "SG",  # St. Gallen
    "AG",  # Aargau
    "TI",  # Ticino
    "VS",  # Valais
    "FR",  # Fribourg
    "SO",  # Solothurn
    "NE",  # Neuchâtel
    "GR",  # Graubünden
    "TG",  # Thurgau
    "ZG",  # Zug
    "SZ",  # Schwyz
    "SH",  # Schaffhausen
    "JU",  # Jura
    "AR",  # Appenzell Ausserrhoden
    "AI",  # Appenzell Innerrhoden
    "GL",  # Glarus
    "NW",  # Nidwalden
    "OW",  # Obwalden
    "UR",  # Uri
]


def query_canton(canton: str, endpoint: str, timeout: float = 65.0) -> List[Dict[str, Any]]:
    query = f"""
    [out:json][timeout:55];
    area["ISO3166-2"="CH-{canton}"][admin_level=4]->.cantonArea;
    (
      node["amenity"~"^(restaurant|cafe|pub|bar|bistro|pizzeria|fast_food)$"](area.cantonArea);
      way["amenity"~"^(restaurant|cafe|pub|bar|bistro|pizzeria|fast_food)$"](area.cantonArea);
    );
    out center tags;
    """
    headers = {"User-Agent": "SwissHousingMap/1.0 (OSM Gastronomy Ingest; contact: dev)"}
    with httpx.Client(timeout=timeout, headers=headers) as client:
        resp = client.post(endpoint, data={"data": query})
        resp.raise_for_status()
        data = resp.json()
        return data.get("elements", [])


def fetch_all_cantons() -> List[Dict[str, Any]]:
    CACHE_DIR.mkdir(parents=True, exist_ok=True)
    all_elements: Dict[str, Dict[str, Any]] = {}

    for canton in SWISS_CANTONS:
        canton_file = CACHE_DIR / f"canton_{canton}.json"

        # Check local cache first
        if canton_file.exists() and canton_file.stat().st_size > 10:
            try:
                with open(canton_file, "r", encoding="utf-8") as f:
                    elements = json.load(f)
                logger.info("Loaded cached canton %s (%d elements)", canton, len(elements))
                for el in elements:
                    el_id = f"{el.get('type', 'node')}_{el.get('id')}"
                    all_elements[el_id] = el
                continue
            except Exception as e:
                logger.warning("Error reading cache %s: %s. Re-fetching.", canton_file, e)

        logger.info("Fetching canton CH-%s...", canton)
        fetched = False
        for endpoint in OVERPASS_ENDPOINTS:
            try:
                elements = query_canton(canton, endpoint)
                with open(canton_file, "w", encoding="utf-8") as f:
                    json.dump(elements, f)
                logger.info("  -> Success on %s for CH-%s: %d elements saved to cache", endpoint, canton, len(elements))
                for el in elements:
                    el_id = f"{el.get('type', 'node')}_{el.get('id')}"
                    all_elements[el_id] = el
                fetched = True
                time.sleep(1.0)
                break
            except Exception as e:
                logger.warning("  Failed on %s for CH-%s: %s. Trying next mirror...", endpoint, canton, e)
                time.sleep(1.0)

        if not fetched:
            logger.error("Could not fetch canton CH-%s from any mirror. Proceeding with others.", canton)

    logger.info("Total unique OSM elements collected across all cantons: %d", len(all_elements))
    return list(all_elements.values())


def process_and_export(elements: List[Dict[str, Any]]) -> Path:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    rows: List[Dict[str, Any]] = []

    for el in elements:
        tags = el.get("tags", {})
        amenity = tags.get("amenity", "restaurant")
        name = tags.get("name") or tags.get("brand")
        if not name:
            cuisine = tags.get("cuisine", "")
            name = f"{cuisine.title()} Restaurant" if cuisine else f"{amenity.capitalize()}"

        # Coordinates (center or point)
        if "lat" in el and "lon" in el:
            lat, lon = float(el["lat"]), float(el["lon"])
        elif "center" in el:
            lat, lon = float(el["center"]["lat"]), float(el["center"]["lon"])
        else:
            continue

        # Convert WGS84 to Swiss LV95
        try:
            gkode, gkodn = wgs84_to_lv95(lat, lon)
        except Exception:
            continue

        # Swiss bounding box verification (EPSG:2056)
        if not (2480000 <= gkode <= 2840000 and 1070000 <= gkodn <= 1300000):
            continue

        osm_id = int(el.get("id", 0))
        street = str(tags.get("addr:street") or "")
        housenumber = str(tags.get("addr:housenumber") or "")
        postcode_raw = tags.get("addr:postcode")
        city = str(tags.get("addr:city") or "")
        cuisine = str(tags.get("cuisine") or "")

        plz = None
        if postcode_raw:
            try:
                plz = int(str(postcode_raw).strip().split()[0])
            except ValueError:
                plz = None

        rows.append({
            "id": osm_id,
            "name": name,
            "shop_type": amenity,
            "cuisine": cuisine,
            "street": street,
            "house_number": housenumber,
            "postal_code": plz,
            "city": city,
            "canton": "",
            "gkode": round(gkode, 2),
            "gkodn": round(gkodn, 2),
            "lat": round(lat, 6),
            "lon": round(lon, 6),
        })

    logger.info("Processed %d valid gastronomy POIs inside Switzerland.", len(rows))

    parquet_file = OUT_DIR / "swiss_restaurants.parquet"
    csv_file = OUT_DIR / "swiss_restaurants.csv"

    # Export using pyarrow
    table = pa.Table.from_pylist(rows)
    pq.write_table(table, parquet_file)

    # Export CSV via DuckDB
    con = duckdb.connect()
    con.register("temp_poi", table)
    con.execute(f"COPY (SELECT id, name, shop_type, street, house_number, postal_code, city, canton, gkode, gkodn FROM temp_poi) TO '{csv_file}' (FORMAT CSV, HEADER);")
    con.close()

    logger.info("Exported %s (%d bytes)", parquet_file, parquet_file.stat().st_size)
    logger.info("Exported %s (%d bytes)", csv_file, csv_file.stat().st_size)
    return parquet_file


def main():
    logger.info("Starting cantonal OpenStreetMap gastronomy POI fetch...")
    elements = fetch_all_cantons()
    if not elements:
        logger.error("No elements fetched.")
        sys.exit(1)
    parquet_path = process_and_export(elements)
    logger.info("Gastronomy ingestion completed successfully: %s", parquet_path)


if __name__ == "__main__":
    main()
