# PRIA field scraper (taotletud põllud)

Downloads the yearly PRIA crop-application field polygons and imports them into
`priadata.pria_history`.

New pipeline: **`pria_scrape.php` → `pria_parse.php`** (shared code in `pria_lib.php`).
The older `spider.php` / `parser.php` / `preg.php` / `import.php` files are kept for
reference but are superseded.

## Quick start

```bash
# 1. Which layer suffix is which year this season? (ALWAYS run this first)
php pria_scrape.php --layers

# 2. Download (resumable, ~2.5 min, ~330 MB on disk gzipped)
php pria_scrape.php --year=2026

# 3. Check what would be imported, without writing
php pria_parse.php --year=2026 --dry-run

# 4. Import
php pria_parse.php --year=2026
```

## The layer-suffix trap

**PRIA layer suffixes rotate every season.** `taotletud_pollud_a_1_v` meant 2025 last
year; it means **2026** now. Suffix `N` is "N-1 years back from the current
application year".

Worse, `GetCapabilities` is unreliable: as of 2026-08-17 the `_1_v` and `_4_v` field
layers are **missing from the capabilities document but still serve data normally**.
Do not use capabilities to decide what exists.

So nothing here hardcodes a suffix. `pria_scrape.php --layers` requests a small
bbox from each layer, reads the `aasta` attribute out of real features, and caches
the mapping to `$baseDir/layer_years.json`. `--year=2026` resolves through that map.
`pria_parse.php` re-checks the year of every feature and refuses to import rows from
a different season, so scraping the wrong layer cannot silently corrupt a year.

Verified mapping on 2026-08-17:

| suffix | layer | year |
|---|---|---|
| 1 | `taotletud_pollud_a_1_v` | **2026** |
| 2 | `taotletud_pollud_a_2_v` | 2025 |
| 3 | `taotletud_pollud_a_3_v` | 2024 |
| 4 | `taotletud_pollud_a_4_v` | 2023 |
| 5 | `taotletud_pollud_a_5_v` | 2022 |
| 6 | `taotletud_pollud_a_6_v` | 2021 |

Use `--refresh` to force a re-probe, or `--suffix=N` to bypass detection entirely.

## What the service actually supports

Probed 2026-08-17:

- **WFS is disabled** (`Service WFS is disabled`), so WMS `GetMap` with `FORMAT=kml`
  is still the only bulk vector export. Attribute values only exist as an HTML
  fragment inside each Placemark's `<description>`, which is why parsing needs regex.
- **Features are returned whole and unclipped.** Two adjacent 13 km tiles shared 132
  features, every one with byte-identical geometry. Tiles therefore need **no
  overlap** — the old 500 m `overhead` was pure waste. Fields straddling a tile edge
  arrive complete from both sides and are deduplicated on `taks_pold_id`.
- **No per-request feature cap was hit.** 13 / 26 / 52 km tiles returned 968 / 3 633 /
  12 491 features, scaling with area. Nothing is being truncated.
- Layer extent (EPSG:3301): `365000, 6375000, 740000, 6635000`.
- Geometry is a `MultiGeometry` of one `Point` (centroid) + one `Polygon`
  (1 outer ring, 0..n inner rings), coordinates in lon,lat WGS84.

## Improvements over `spider.php` / `parser.php`

| | old | new |
|---|---|---|
| Year selection | hardcoded suffix, edited by hand each season | probed from feature data, verified again at import |
| Tiles | 13 km + 500 m overlap → ~650 requests | 26 km, no overlap → 150 requests |
| Requests | sequential, `sleep(1)` between each | `curl_multi`, configurable concurrency |
| Error handling | response written to disk unchecked | validates KML, detects service exceptions and truncated transfers, retries with backoff |
| Resume | none — restart re-downloaded everything | manifest-tracked; atomic writes so a killed run leaves no half tile |
| KML→GeoJSON | manual `ogr2ogr` bash one-liner between the two steps | none needed, KML parsed directly |
| Memory | whole GeoJSON per tile via `json_decode` | `XMLReader` streams one Placemark at a time |
| Tile discovery | `for ($i=1; $i<652; $i++)` hardcoded count | globs whatever is on disk |
| Duplicates | relied on MySQL errno 1062 per row | deduplicated in-process |
| Writes | one autocommit insert per row | prepared upsert in transactions |
| Disk | ~3.0 GB (kml + geojson) | ~330 MB (gzipped kml only) |

The direct KML parser was cross-validated against the old `ogr2ogr` path on a
206-feature tile: **polygons, centroids and attributes were byte-identical for all
206 features.** Coordinate order is deliberately left as KML's lon,lat so the GeoJSON
handed to `ST_GeomFromGeoJSON()` matches what `ogr2ogr` produced. MySQL then applies
EPSG:4326 lat,lon axis order on top, which is why `ST_X(geom_centroid)` returns
*latitude* for both old and new rows. **Do not "fix" this ordering** — it would break
compatibility with every row already stored.

## 2026 run (2026-08-17)

```
scrape:  150 tiles, 1.4 GB raw KML → 327 MB gzipped, 2m16s
parse:   181 891 features read → 160 702 unique (21 189 cross-tile duplicates)
         0 missing geometry, 0 wrong year, 0 failed rows, 5m30s
```

Result sits normally alongside previous seasons:

| year | fields | total ha | avg ha | applicants | crops |
|---|---|---|---|---|---|
| 2023 | 161 248 | 905 480 | 5.62 | 3 916 | 242 |
| 2024 | 159 141 | 910 283 | 5.72 | 3 957 | 252 |
| 2025 | 163 513 | 938 975 | 5.74 | 4 011 | 249 |
| **2026** | **160 702** | **936 955** | **5.83** | **4 144** | **252** |

Centroid bounds: lat 57.518–59.635, lon 21.844–28.156. Correct for Estonia.

### Known data quality note

About **1.2 % of polygons are invalid** (`ST_IsValid = 0`), mostly self-intersections.
This is inherent to PRIA's source data, not the parser — sampling 20 000 rows each
gives 1.20 % for 2025 (old pipeline) and 1.19 % for 2026 (new). MySQL has no
`ST_MakeValid`, so these cannot currently be repaired in the database. PostGIS does —
see `docs/mysql_to_postgresql_migration.md`.

## Options

`pria_scrape.php`

| option | default | meaning |
|---|---|---|
| `--year=YYYY` | required | year to fetch (resolved to a layer by probing) |
| `--layers` | | print suffix→year map and exit |
| `--tile=METRES` | `26000` | tile size |
| `--concurrency=N` | `4` | parallel requests — keep modest, it is a public service |
| `--force` | | re-download tiles already on disk |
| `--refresh` | | re-probe the year map instead of using the cache |
| `--suffix=N` | | skip detection and use this layer suffix |
| `--dry-run` | | print the URLs that would be fetched |

`pria_parse.php`

| option | default | meaning |
|---|---|---|
| `--year=YYYY` | required | year to import; rows of any other year are refused |
| `--dry-run` | | parse and report, write nothing |
| `--batch=N` | `500` | rows per transaction |

## Storage layout

```
$baseDir/layer_years.json         # cached suffix -> year map
$baseDir/2026/manifest.json       # per-tile bytes/features/bbox, drives resume
$baseDir/2026/tiles/{col}_{row}.kml.gz
```

`$baseDir` comes from `conf.php`.

Resume is driven by the manifest rather than by file size on purpose. A genuinely
empty tile — sea, or across the border — is a valid ~468 byte gzip, so any "larger
than N bytes means complete" rule re-downloads all 49 empty tiles on every run.
A tile counts as done only when the manifest records it *and* the file on disk
still matches the recorded size.
