"""Download OpenStreetMap Schools, Daycares, Kindergartens, and Crèches for Switzerland.

Queries Overpass API canton-by-canton with resilient retries, caching each canton
to data/raw/schools/cache/. Transforms WGS84 coordinates to Swiss LV95 (EPSG:2056)
and exports clean parquet and CSV to data/raw/schools/.
"""

from __future__ import annotations

import json
import logging
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/schools/cache")
OUT_DIR = Path("data/raw/schools")

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

# 26 Swiss Cantons
SWISS_CANTONS = [
    "GE",  # Genève (Corsier, etc.)
    "VD",  # Vaud (Pully, Lausanne, Montreux)
    "ZH",  # Zürich
    "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"~"^(kindergarten|childcare|preschool|creche|school)$"](area.cantonArea);
      way["amenity"~"^(kindergarten|childcare|preschool|creche|school)$"](area.cantonArea);
    );
    out center tags;
    """
    headers = {"User-Agent": "SwissHousingMap/1.0 (OSM Schools & Daycares 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 school/daycare elements collected: %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", "school").lower()
        name = tags.get("name") or tags.get("description")

        if amenity in ("kindergarten", "childcare", "preschool", "creche"):
            facility_type = "daycare"
            if not name:
                name = "Crèche / Garderie / Kindergarten"
        else:
            facility_type = "school"
            if not name:
                name = "École / Primarschule"

        # 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 "")

        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,
            "facility_type": facility_type,
            "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 school and daycare POIs inside Switzerland.", len(rows))

    parquet_file = OUT_DIR / "swiss_schools_daycares.parquet"
    csv_file = OUT_DIR / "swiss_schools_daycares.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, facility_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 schools & daycares fetch...")
    elements = fetch_all_cantons()
    if not elements:
        logger.error("No elements fetched.")
        sys.exit(1)
    parquet_path = process_and_export(elements)
    logger.info("Schools & daycares ingestion completed successfully: %s", parquet_path)


if __name__ == "__main__":
    main()
