-- Tennis court locations from OpenStreetMap via Overpass API (sport=tennis).
-- Used as a "racket sport culture" signal in the opportunity score:
-- areas with high tennis court density are prime padel adoption markets.
--
-- Source: data/landing/overpass_tennis/{year}/{month}/courts.jsonl.gz
-- Format: one OSM element per line; nodes have lat/lon directly,
--         ways/relations have center.lat/center.lon (Overpass out center)

MODEL (
  name staging.stg_tennis_courts,
  kind FULL,
  cron '@daily',
  grain osm_id
);

WITH
parsed AS (
  SELECT
    type                                                          AS osm_type,
    TRY_CAST(id AS BIGINT)                                        AS osm_id,
    -- Nodes: lat/lon direct. Ways/relations: center object (Overpass out center).
    COALESCE(
      TRY_CAST(lat AS DOUBLE),
      TRY_CAST(center ->> 'lat' AS DOUBLE)
    )                                                             AS lat,
    COALESCE(
      TRY_CAST(lon AS DOUBLE),
      TRY_CAST(center ->> 'lon' AS DOUBLE)
    )                                                             AS lon,
    tags ->> 'name'                                               AS name,
    tags ->> 'addr:country'                                       AS country_code,
    tags ->> 'addr:city'                                          AS city_tag,
    filename                                                      AS source_file,
    CURRENT_DATE                                                  AS extracted_date
  FROM read_json(
    @LANDING_DIR || '/overpass_tennis/*/*/courts.jsonl.gz',
    format = 'newline_delimited',
    columns = {
      type: 'VARCHAR', id: 'BIGINT', lat: 'DOUBLE', lon: 'DOUBLE',
      center: 'JSON', tags: 'JSON'
    },
    filename = true
  )
  WHERE type IS NOT NULL
),
deduped AS (
  SELECT *,
    ROW_NUMBER() OVER (PARTITION BY osm_id ORDER BY extracted_date DESC) AS rn
  FROM parsed
  WHERE lat IS NOT NULL AND lon IS NOT NULL
    AND lat BETWEEN -90  AND 90
    AND lon BETWEEN -180 AND 180
),
with_country AS (
  SELECT
    osm_id, lat, lon,
    COALESCE(NULLIF(TRIM(UPPER(country_code)), ''),
             @infer_country_from_coords(lat, lon)) AS country_code,
    NULLIF(TRIM(name), '')     AS name,
    NULLIF(TRIM(city_tag), '') AS city,
    extracted_date
  FROM deduped
  WHERE rn = 1
)
SELECT
  osm_id,
  lat,
  lon,
  country_code,
  name,
  city,
  extracted_date
FROM with_country
