# create_building_footprints.R
# Pull Sarasota County building footprints clipped to St. Andrews boundary.
# Source: https://ags3.scgov.net/server/rest/services/Hosted/BuildingFootprint/FeatureServer/0
# Output: data-raw/sarco/building_footprints/building_footprints.gpkg
# No esri2sf needed — queries ArcGIS REST API directly via GeoJSON URL.

library(sf)
library(dplyr)

# load st. andrews subdivision boundary ----
plats <- st_read("./data/plats/plats.shp", quiet = TRUE) |> st_transform(4326)
boundary <- st_union(plats)
bb <- st_bbox(boundary)

# build arcgis rest query url ----
base_url <- "https://ags3.scgov.net/server/rest/services/Hosted/BuildingFootprint/FeatureServer/0/query"
geometry  <- paste(bb["xmin"], bb["ymin"], bb["xmax"], bb["ymax"], sep = ",")
params <- paste0(
  "?where=1=1",
  "&geometry=", geometry,
  "&geometryType=esriGeometryEnvelope",
  "&inSR=4326",
  "&spatialRel=esriSpatialRelIntersects",
  "&outFields=*",
  "&returnGeometry=true",
  "&f=geojson"
)
url <- paste0(base_url, params)
cat("URL:\n", url, "\n\n")

# fetch ----
cat("Querying feature service...\n")
footprints_raw <- st_read(url, quiet = TRUE)
cat("Raw rows:", nrow(footprints_raw), "\n")
cat("Raw fields:", paste(names(footprints_raw), collapse = ", "), "\n\n")

# clip to exact subdivision boundary ----
footprints <- footprints_raw |>
  st_transform(4326) |>
  st_filter(boundary)

# inspect ----
cat("Rows:", nrow(footprints), "\n")
cat("\nFields:\n")
print(names(footprints))
cat("\nSample rows:\n")
print(head(st_drop_geometry(footprints)))

# save ----
st_write(
  footprints,
  "./data-raw/sarco/building_footprints/building_footprints.gpkg",
  delete_dsn = TRUE
)

cat("\nSaved to data-raw/sarco/building_footprints/building_footprints.gpkg\n")
