File size: 24,043 Bytes
7fd88a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
#!/usr/bin/env python3
"""Download a provenance-rich market snapshot from live web services.

Sources:
- Catastro: public, non-protected parcel data by coordinates or Spanish address.
- INE: public Tempus JSON API for the Housing Price Index (IPV).
- Registradores (v18): open-data CSV of real notarised sale prices per m2
  (``role="transaction_price"``); counts toward the price leg with Idealista.
- MIVAU (v18 round 5): Ministerio de Vivienda Boletín Estadístico tables —
  appraisal EUR/m2 (``appraisal_price_m2``) and mean value per transaction
  (``transaction_value_avg``); cross-checks only, never the price leg; ``xlrd``
  is a hard dependency since v19 (missing -> ``ERROR``).
- INE ETDP (v19): monthly housing sales counts by CCAA (table 6150,
  ``transaction_count``); replaces the dead table 6171.
- Idealista: live listings when IDEALISTA_API_KEY and IDEALISTA_API_SECRET are set.
- CartoCiudad (IGN, v19): geocoder used only to snap a loose point / rejected
  address onto a real cadastral parcel; recorded under ``catastro.data.geocoding``.

The collector never substitutes embedded reference prices for a failed web request.
It prints JSON to stdout unless --output is explicitly supplied. A partial or failed
snapshot remains useful as evidence, but must not be presented as a current complete
market valuation.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from dataclasses import asdict
from datetime import date, datetime, timezone
from pathlib import Path
from typing import Any

SCRIPT_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(SCRIPT_DIR))

from agent_version import AGENT_VERSION  # noqa: E402
from catastro_idealista_real import (  # noqa: E402
    CartoCiudadGeocoder,
    CatastroReal,
    IdealistaReal,
    IDEALISTA_SEARCH_URL,
)
from market_intelligence import (  # noqa: E402
    INE_ETDP_COMPRAVENTAS_TABLE,
    INE_IPV_BASE_YEAR,
    INE_IPV_TABLE,
    INEPrices,
    MivauPrices,
    PROVINCE_TO_CCAA,
    RegistradoresPrices,
    ine_cadence_assessment,
    registradores_cadence_assessment,
    registradores_period_label,
)

SCHEMA_VERSION = ".".join(AGENT_VERSION.split(".")[:2])  # e.g. "16.0"


def utc_now() -> str:
    """Return a compact ISO-8601 UTC timestamp."""
    return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")


def source_record(source_id: str, name: str, kind: str, url: str,
                  status: str, retrieved_at: str, data: Any = None,
                  error: str = "", coverage: str = "",
                  data_date: str = "", role: str = "") -> dict[str, Any]:
    """Build a normalized source record without credentials."""
    record: dict[str, Any] = {
        "id": source_id,
        "name": name,
        "kind": kind,
        "url": url,
        "status": status,
        "retrieved_at": retrieved_at,
        "coverage": coverage,
        "data_date": data_date,
        "role": role,
    }
    if error:
        record["error"] = error
    if data is not None:
        record["data"] = data
    return record


def collect_catastro(lat: float | None, lon: float | None,
                     province: str, municipality: str, street: str,
                     number: str, retrieved_at: str) -> tuple[dict[str, Any], float | None, float | None]:
    """Download Catastro data and return its record plus resolved coordinates.

    v19: a lat/lon that lands on no parcel is snapped to the nearest CartoCiudad
    portal (<= 150 m) by :meth:`CatastroReal.full_lookup_resilient`; an address
    the Catastro callejero rejects is geocoded with CartoCiudad and looked up
    at that point. ``data.geocoding`` records what happened; the returned
    coordinates are the ones the parcel was actually found at.
    """
    geocoding: dict[str, Any] = {"service": "CartoCiudad (IGN)", "used": False}
    if lat is not None and lon is not None:
        parcel = CatastroReal.full_lookup_resilient(lat, lon)
        request_url = f"{CatastroReal.__module__}:Consulta_RCCOOR/Consulta_DNPRC"
        if parcel.resolved_via == "cartociudad_reverse_snap":
            geocoding.update({"used": True, "mode": "reverse_snap",
                              "snapped_to": parcel.geocoder_address,
                              "snap_distance_m": parcel.snap_distance_m,
                              "snapped_coordinates": list(parcel.snapped_coordinates)})
    else:
        parcel = CatastroReal.locate(
            provincia=province, municipio=municipality, calle=street, numero=number)
        request_url = f"{CatastroReal.__module__}:Consulta_DNPLOC/Consulta_CPMRC"
        if parcel.error or not parcel.ref_catastral:
            geo = CartoCiudadGeocoder.geocode(f"{street} {number}, {municipality}")
            geocoding.update({"used": True, "mode": "address", "query": f"{street} {number}, {municipality}",
                              "result": {"ok": geo.ok, "address": geo.address, "type": geo.type,
                                         "precision": geo.precision, "parcel_grade": geo.parcel_grade,
                                         "lat": geo.lat, "lon": geo.lon, "ref_catastral": geo.ref_catastral,
                                         "error": geo.error}})
            if geo.ok and geo.parcel_grade:        # portal-level only: never a street centroid
                alt = CatastroReal.by_refcat(geo.ref_catastral) if geo.ref_catastral else None
                if alt is None or alt.error or not alt.ref_catastral:
                    alt = CatastroReal.full_lookup_resilient(geo.lat, geo.lon)
                if not alt.error and alt.ref_catastral:
                    alt.coordinates = (geo.lat, geo.lon)
                    alt.resolved_via = "cartociudad_address"
                    geocoding["catastro_error_before"] = parcel.error or "sin parcela"
                    parcel = alt
                else:
                    geocoding["catastro_error_after"] = alt.error or "sin parcela"
    payload = asdict(parcel)
    error = str(payload.get("error", ""))
    status = "ERROR" if error or not payload.get("ref_catastral") else "LIVE"
    resolved = payload.get("coordinates") or (0.0, 0.0)
    if parcel.resolved_via == "cartociudad_reverse_snap" and parcel.snapped_coordinates != (0.0, 0.0):
        resolved = parcel.snapped_coordinates      # where the parcel really is
    resolved_lat = float(resolved[0]) if tuple(resolved) != (0.0, 0.0) else lat
    resolved_lon = float(resolved[1]) if tuple(resolved) != (0.0, 0.0) else lon
    record = source_record(
        "catastro", "Dirección General del Catastro", "parcel",
        "https://www.catastro.hacienda.gob.es/ws/", status, retrieved_at,
        data={"request": request_url, "parcel": payload, "geocoding": geocoding}, error=error,
        coverage="Spain; public non-protected cadastral fields",
        data_date=retrieved_at,
        role="parcel_identity",
    )
    return record, resolved_lat, resolved_lon


def latest_ine_period(result: dict[str, Any]) -> str:
    """Return the latest source period (``"2025 T4"``) found in an INE response.

    v16.0.1: ordered numerically by (year, quarter) instead of by string, and a
    record whose quarter could not be resolved is NOT reduced to a bare year.
    The live capture of 2026-09-15 showed ``quarter == ""`` for every record
    (wrong field name upstream) and this function then returned ``"2025"``,
    which Opposition Tierra resolves to 31 December: a label that can hide up
    to twelve months of staleness. If no record carries a quarter label the
    function returns ``""`` so the reviewer raises SRC-008 instead.
    """
    best: tuple[int, int] | None = None
    for values in result.get("series", {}).values():
        for value in values:
            year = value.get("year")
            quarter = str(value.get("quarter") or "").strip().upper()
            if year is None or not quarter:
                continue
            digits = "".join(ch for ch in quarter if ch.isdigit())
            if not digits:
                continue
            try:
                key = (int(year), int(digits))
            except (TypeError, ValueError):
                continue
            if best is None or key > best:
                best = key
    if best is None:
        return ""
    return f"{best[0]} T{best[1]}"


def collect_ine(periods: int, retrieved_at: str, today: date | None = None) -> list[dict[str, Any]]:
    """Download the official INE Housing Price Index table.

    v17: reads table :data:`INE_IPV_TABLE` (80270, base 2025; v16 read the
    base-2015 table 25171 that INE stopped at 2025 T4) and compares the newest
    period with the INE publication calendar (:func:`ine_cadence_assessment`).
    A table that is at least one published quarter behind is reported with
    ``status = "STALE"`` — not ``LIVE`` — so the snapshot degrades to
    ``PARTIAL_LIVE`` and Opposition Tierra raises SRC-005 with the reason in
    ``error``, instead of an SRC-009 "days old" figure that reads like normal
    lag. The assessment itself is attached as ``cadence``.
    """
    records: list[dict[str, Any]] = []
    for source_id, table_id, getter, coverage in (
        ("ine_ipv", INE_IPV_TABLE, INEPrices.get_ipv,
         f"Housing Price Index by CCAA (INE Tempus table {INE_IPV_TABLE}, base {INE_IPV_BASE_YEAR})"),
    ):
        result = getter(periods=periods)
        status = "LIVE" if result.get("status") == "ok" else "ERROR"
        error = str(result.get("message") or result.get("code") or "") if status == "ERROR" else ""
        data_date = latest_ine_period(result)
        cadence: dict[str, Any] | None = None
        if status == "LIVE":
            cadence = ine_cadence_assessment(data_date, today)
            if cadence["assessment"] == "STALE":
                status = "STALE"
                error = f"INE table {table_id} is stale: {cadence['note']}"
        record = source_record(
            source_id, "Instituto Nacional de Estadística", "market",
            INEPrices.ipv_url(periods, table_id),
            status, retrieved_at, data=result, error=error,
            coverage=coverage,
            data_date=data_date,
            role="price_index",
        )
        if cadence is not None:
            record["cadence"] = cadence
        records.append(record)
    return records


def collect_ine_transactions(ccaa: str, retrieved_at: str, periods: int = 12) -> dict[str, Any]:
    """Monthly housing sales counts from INE ETDP table 6150 (v19, replaces dead 6171).

    ``role="transaction_count"``: a volume, not a price — never part of the price
    leg of :func:`derive_status`. ``ccaa`` is the same key the Registradores
    collector uses (``"nacional"`` when unknown). ``data_date`` is the latest
    month present (``"2026 M06"``).
    """
    result = INEPrices.get_transactions(periods=periods, ccaa=ccaa)
    status = "LIVE" if result.get("status") == "ok" else "ERROR"
    error = str(result.get("message") or result.get("code") or "") if status == "ERROR" else ""
    latest = result.get("latest") or {}
    return source_record(
        "ine_etdp_compraventas", "Instituto Nacional de Estadística — ETDP", "market",
        str(result.get("url") or INEPrices.transactions_url(periods)),
        status, retrieved_at, data=result, error=error,
        coverage=(f"Compraventas de viviendas (número, mensual) por CCAA y provincia — INE Tempus "
                  f"table {INE_ETDP_COMPRAVENTAS_TABLE}; General / nueva / segunda mano / libre / protegida"),
        data_date=str(latest.get("period", "")) if status == "LIVE" else "",
        role="transaction_count",
    )


def collect_registradores(ccaa: str, retrieved_at: str, today: date | None = None) -> dict[str, Any]:
    """Download the Colegio de Registradores real notarized transaction-price dataset.

    v18: an additional, credential-free market source alongside the INE index
    (``ine_ipv``, ``role="price_index"``) and the optional Idealista listings
    (``idealista``, ``role="asking_price"``). ``role="transaction_price"`` —
    the actual sale price per m² of registered residential transactions that
    quarter, never blurred with either an index or an asking price. ``ccaa``
    defaults to ``"nacional"`` when the caller cannot resolve one from the
    query (this module has no province/CCAA lookup for lat/lon queries; a
    caller that already knows the province may pass its CCAA key).

    v18 round 5: the record carries ``cadence`` (same shape as the INE one)
    and is ``STALE`` — not ``LIVE`` — when the file read stops at least one
    quarter before the (single-observation) publication calendar expects,
    which is exactly what happens if the pinned filename keeps serving an old
    file after the portal moved on; the URL actually read and how it was
    resolved (``pinned`` / ``dataset_page``) are in ``data``.
    """
    result = RegistradoresPrices.get_compraventas(ccaa)
    status = "LIVE" if result.get("status") == "ok" else "ERROR"
    error = str(result.get("message") or result.get("code") or "") if status == "ERROR" else ""
    data_date = registradores_period_label(result.get("latest") or {}) if status == "LIVE" else ""
    cadence: dict[str, Any] | None = None
    if status == "LIVE":
        cadence = registradores_cadence_assessment(data_date, today)
        if cadence["assessment"] == "STALE":
            status = "STALE"
            error = f"Registradores dataset is stale: {cadence['note']}"
    record = source_record(
        "registradores", "Colegio de Registradores de España — Estadística Registral Inmobiliaria",
        "market", str(result.get("url") or RegistradoresPrices.URL), status, retrieved_at,
        data=result, error=error,
        coverage="Real notarized residential sale prices per m² by CCAA (quarterly, 2007-present)",
        data_date=data_date,
        role="transaction_price",
    )
    if cadence is not None:
        record["cadence"] = cadence
    return record


MIVAU_SOURCE_IDS = {
    "valor_tasado_vivienda_libre": "mivau_valor_tasado",
    "valor_medio_transaccion_vivienda_libre": "mivau_valor_medio_transaccion",
}


def collect_mivau(ccaa: str, retrieved_at: str) -> list[dict[str, Any]]:
    """Download the two Ministerio de Vivienda (MIVAU) Boletín Estadístico tables (v18).

    Cross-check sources, NOT part of the price leg of :func:`derive_status`:
    - ``mivau_valor_tasado`` (``role="appraisal_price_m2"``, EUR/m2): mean
      ECO/805 appraisal value — an appraisal is not a sale;
    - ``mivau_valor_medio_transaccion`` (``role="transaction_value_avg"``, EUR
      per transaction): mean declared value per notarised sale, per dwelling,
      not per m2.
    v19: ``xlrd`` is a hard dependency; if it is somehow missing the records are
    ``ERROR`` (broken environment), no longer an "expected" ``SKIPPED``.
    """
    records: list[dict[str, Any]] = []
    for table_key, source_id in MIVAU_SOURCE_IDS.items():
        spec = MivauPrices.TABLES[table_key]
        result = MivauPrices.get_table(table_key, ccaa)
        if result.get("status") == "ok":
            status, error = "LIVE", ""
        elif result.get("status") == "skipped":
            status, error = "SKIPPED", str(result.get("message", ""))
        else:
            status, error = "ERROR", str(result.get("message") or result.get("code") or "")
        latest = result.get("latest") or {}
        data_date = str(latest.get("period", "")) if status == "LIVE" else ""
        records.append(source_record(
            source_id, f"Ministerio de Vivienda y Agenda Urbana — {spec['title']}",
            "market", str(result.get("url") or MivauPrices.BASE + spec["file"]), status, retrieved_at,
            data=result, error=error,
            coverage=f"{spec['unit']} by CCAA and province, quarterly; {spec['nature']}",
            data_date=data_date,
            role=spec["role"],
        ))
    return records


def collect_idealista(lat: float | None, lon: float | None, radius: int,
                      retrieved_at: str) -> dict[str, Any]:
    """Download live Idealista listings or return an explicit credential/coordinate status."""
    if lat is None or lon is None:
        return source_record(
            "idealista", "Idealista", "market", IDEALISTA_SEARCH_URL,
            "SKIPPED", retrieved_at, error="Coordinates unavailable after Catastro lookup.",
            coverage=f"Spain sale listings within {radius} metres",
            data_date="",
            role="asking_price",
        )
    if not os.environ.get("IDEALISTA_API_KEY") or not os.environ.get("IDEALISTA_API_SECRET"):
        return source_record(
            "idealista", "Idealista", "market", IDEALISTA_SEARCH_URL,
            "SKIPPED", retrieved_at,
            error="IDEALISTA_API_KEY and IDEALISTA_API_SECRET are not configured.",
            coverage=f"Spain sale listings within {radius} metres",
            data_date="",
            role="asking_price",
        )
    result = IdealistaReal.search(lat, lon, distance=radius)
    payload = asdict(result)
    error = str(payload.get("error", ""))
    status = "LIVE" if not error else "ERROR"
    return source_record(
        "idealista", "Idealista", "market", IDEALISTA_SEARCH_URL,
        status, retrieved_at, data=payload, error=error,
        coverage=f"Spain sale listings within {radius} metres",
        data_date=retrieved_at,
        role="asking_price",
    )


CORE_MARKET_SOURCE_IDS = {"catastro", "ine_ipv"}
PRICE_OBSERVATION_SOURCE_IDS = {"idealista", "registradores"}


def derive_status(sources: list[dict[str, Any]]) -> str:
    """Derive LIVE, PARTIAL_LIVE, or NO_LIVE_MARKET_DATA from source outcomes.

    Only ``LIVE`` counts; ``STALE`` (v17: INE table behind its own calendar),
    ``ERROR`` and ``SKIPPED`` all degrade the snapshot.

    v18: the price leg is Idealista OR Registradores, not Idealista alone —
    Idealista requires API credentials the owner may not have; Registradores
    needs none. When both are present, either one being ``LIVE`` satisfies the
    price leg (this is the whole point of adding a second source: a snapshot
    with no Idealista credentials but a live Registradores fetch now reaches
    ``LIVE`` instead of being permanently capped at ``PARTIAL_LIVE``). When
    neither price source is present in ``sources`` at all, the price leg is
    skipped entirely — same behaviour as before this source existed.
    """
    by_id = {source.get("id"): source for source in sources if isinstance(source, dict)}
    core = [by_id[i] for i in CORE_MARKET_SOURCE_IDS if i in by_id]
    price = [by_id[i] for i in PRICE_OBSERVATION_SOURCE_IDS if i in by_id]
    live_core = [source for source in core if source.get("status") == "LIVE"]
    live_price = [source for source in price if source.get("status") == "LIVE"]
    if not core and not price:
        return "NO_LIVE_MARKET_DATA"
    core_ok = bool(core) and len(live_core) == len(core)
    price_ok = (not price) or bool(live_price)
    if core_ok and price_ok:
        return "LIVE"
    if live_core or live_price:
        return "PARTIAL_LIVE"
    return "NO_LIVE_MARKET_DATA"


def resolve_registradores_ccaa(province: str) -> str:
    """Best-effort ``province`` (as typed by the caller) -> Registradores CCAA key.

    Reuses :data:`market_intelligence.PROVINCE_TO_CCAA` (already built for the
    Idealista/Catastro province flow). Falls back to ``"nacional"`` — never
    guesses a wrong CCAA — when the province is empty or not in the map (e.g.
    a lat/lon query, which this module cannot reverse-geocode to a province).
    """
    key = (province or "").strip().lower()
    return PROVINCE_TO_CCAA.get(key, "nacional")


def collect_market_data(*, lat: float | None = None, lon: float | None = None,
                        province: str = "", municipality: str = "",
                        street: str = "", number: str = "", radius: int = 1000,
                        periods: int = 8) -> dict[str, Any]:
    """Collect Catastro, INE, Registradores, MIVAU and optional Idealista data into one evidence snapshot."""
    retrieved_at = utc_now()
    catastro, resolved_lat, resolved_lon = collect_catastro(
        lat, lon, province, municipality, street, number, retrieved_at)
    sources = [catastro]
    sources.extend(collect_ine(periods, retrieved_at))
    ccaa = resolve_registradores_ccaa(province)
    if ccaa == "nacional" and catastro.get("status") == "LIVE":
        # v19: a lat/lon query has no province; the parcel Catastro returned does.
        ccaa = resolve_registradores_ccaa(str(catastro["data"]["parcel"].get("provincia") or ""))
    sources.append(collect_ine_transactions(ccaa, retrieved_at))
    sources.append(collect_registradores(ccaa, retrieved_at))
    sources.extend(collect_mivau(ccaa, retrieved_at))
    sources.append(collect_idealista(resolved_lat, resolved_lon, radius, retrieved_at))
    status = derive_status(sources)
    return {
        "schema_version": SCHEMA_VERSION,
        "agent_version": AGENT_VERSION,
        "status": status,
        "retrieved_at": retrieved_at,
        "query": {
            "lat": lat, "lon": lon, "province": province,
            "municipality": municipality, "street": street,
            "number": number, "radius_m": radius, "periods": periods,
        },
        "resolved_coordinates": {"lat": resolved_lat, "lon": resolved_lon},
        "sources": sources,
        "decision_policy": (
            "Current conclusions require LIVE. PARTIAL_LIVE is conditional. "
            "NO_LIVE_MARKET_DATA blocks current valuation and viability conclusions."
        ),
    }


def build_parser() -> argparse.ArgumentParser:
    """Build the side-effect-free command-line parser."""
    parser = argparse.ArgumentParser(
        description=f"Download a live market-data snapshot (agent v{AGENT_VERSION})")
    parser.add_argument("--lat", type=float)
    parser.add_argument("--lon", type=float)
    parser.add_argument("--province", default="")
    parser.add_argument("--municipality", default="")
    parser.add_argument("--street", default="")
    parser.add_argument("--number", default="")
    parser.add_argument("--radius", type=int, default=1000)
    parser.add_argument("--periods", type=int, default=8)
    parser.add_argument("--output", help="Optional output JSON path; defaults to stdout")
    return parser


def validate_query(args: argparse.Namespace) -> str:
    """Return an input error message, or an empty string for a valid query."""
    has_coords = args.lat is not None or args.lon is not None
    if has_coords and (args.lat is None or args.lon is None):
        return "--lat and --lon must be supplied together"
    has_address = any((args.province, args.municipality, args.street, args.number))
    if not has_coords and not all((args.province, args.municipality, args.street, args.number)):
        return "supply --lat/--lon or all of --province/--municipality/--street/--number"
    if has_coords and has_address:
        return "choose coordinates or address, not both"
    if args.radius <= 0 or args.periods <= 0:
        return "--radius and --periods must be greater than zero"
    return ""


def main() -> int:
    """Run the collector and return a process exit code."""
    args = build_parser().parse_args()
    error = validate_query(args)
    if error:
        print(json.dumps({"status": "INPUT_ERROR", "error": error}, ensure_ascii=False))
        return 2
    snapshot = collect_market_data(
        lat=args.lat, lon=args.lon, province=args.province,
        municipality=args.municipality, street=args.street, number=args.number,
        radius=args.radius, periods=args.periods,
    )
    rendered = json.dumps(snapshot, ensure_ascii=False, indent=2)
    if args.output:
        Path(args.output).write_text(rendered + "\n", encoding="utf-8")
    else:
        print(rendered)
    return 0 if snapshot["status"] == "LIVE" else 1


if __name__ == "__main__":
    raise SystemExit(main())