"""Overpass API extractor — global padel court locations from OpenStreetMap.

Queries the Overpass API for all nodes/ways/relations tagged sport=padel
and writes the raw OSM JSON to the landing zone.

Landing: {LANDING_DIR}/overpass/{year}/{month}/courts.json.gz
"""

import sqlite3
from pathlib import Path

import niquests

from ._shared import OVERPASS_TIMEOUT_SECONDS, post_overpass, run_extractor, setup_logging
from .utils import landing_path, write_gzip_atomic

logger = setup_logging("padelnomics.extract.overpass")

EXTRACTOR_NAME = "overpass"

OVERPASS_QUERY = (
    "[out:json][timeout:60];\n"
    "(\n"
    '  node["sport"="padel"];\n'
    '  way["sport"="padel"];\n'
    '  relation["sport"="padel"];\n'
    ");\n"
    "out body;"
)


def extract(
    landing_dir: Path,
    year_month: str,
    conn: sqlite3.Connection,
    session: niquests.Session,
) -> dict:
    """POST OverpassQL query and write raw OSM JSON. Returns run metrics."""
    year, month = year_month.split("/")
    dest_dir = landing_path(landing_dir, "overpass", year, month)
    dest = dest_dir / "courts.json.gz"

    logger.info("POST Overpass (with mirror fallback)")
    resp = post_overpass(session, OVERPASS_QUERY, OVERPASS_TIMEOUT_SECONDS)

    size_bytes = len(resp.content)
    logger.info("%s bytes received", f"{size_bytes:,}")

    bytes_written = write_gzip_atomic(dest, resp.content)
    logger.info("wrote %s (%s bytes compressed)", dest, f"{bytes_written:,}")

    return {
        "files_written": 1,
        "files_skipped": 0,
        "bytes_written": bytes_written,
        "cursor_value": year_month,
    }


def main() -> None:
    run_extractor(EXTRACTOR_NAME, extract)


if __name__ == "__main__":
    main()
