File size: 28,362 Bytes
7b97ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd88a5
 
 
 
7b97ccd
7fd88a5
7b97ccd
3915cb6
 
 
 
 
 
7fd88a5
7b97ccd
e28bc7a
7b97ccd
7fd88a5
7b97ccd
 
 
 
 
 
7fd88a5
 
e28bc7a
 
 
 
 
 
 
 
 
7b97ccd
 
 
 
 
2461d8f
7b97ccd
 
 
2461d8f
7b97ccd
 
 
 
 
 
2461d8f
 
7b97ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2461d8f
 
7b97ccd
 
 
 
 
2461d8f
7b97ccd
 
 
2461d8f
7b97ccd
 
 
 
 
 
2461d8f
 
7b97ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2461d8f
 
7b97ccd
e28bc7a
 
 
 
2461d8f
e28bc7a
 
 
2461d8f
e28bc7a
 
 
 
 
 
2461d8f
 
e28bc7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2461d8f
 
e28bc7a
7fd88a5
 
 
7b97ccd
 
7fd88a5
 
7b97ccd
2461d8f
 
 
7b97ccd
2461d8f
7b97ccd
 
 
 
 
 
 
 
 
 
 
7fd88a5
7b97ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3915cb6
 
7b97ccd
 
 
3915cb6
 
 
 
7b97ccd
3915cb6
 
 
 
 
 
 
 
 
 
 
 
 
 
7b97ccd
 
 
2461d8f
 
 
 
3915cb6
2461d8f
 
 
 
 
 
 
 
 
 
 
 
 
7b97ccd
 
7fd88a5
7b97ccd
 
 
 
2461d8f
 
7b97ccd
3915cb6
7b97ccd
 
 
3915cb6
7b97ccd
 
 
 
 
 
 
 
3915cb6
7b97ccd
 
 
 
 
2461d8f
 
 
7b97ccd
 
 
 
 
3915cb6
 
7b97ccd
 
 
 
 
 
 
 
2461d8f
 
7b97ccd
2461d8f
 
 
7b97ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd88a5
7b97ccd
7fd88a5
 
 
 
7b97ccd
7fd88a5
7b97ccd
7fd88a5
 
 
7b97ccd
 
 
7fd88a5
 
 
 
 
 
7b97ccd
 
7fd88a5
e28bc7a
 
7b97ccd
 
e28bc7a
7b97ccd
2461d8f
 
7b97ccd
7fd88a5
 
7b97ccd
 
 
 
 
7fd88a5
7b97ccd
 
 
7fd88a5
7b97ccd
7fd88a5
7b97ccd
 
7fd88a5
7b97ccd
 
7fd88a5
 
7b97ccd
7fd88a5
7b97ccd
 
7fd88a5
7b97ccd
 
 
 
 
7fd88a5
7b97ccd
7fd88a5
7b97ccd
7fd88a5
 
7b97ccd
 
 
7fd88a5
7b97ccd
 
 
 
7fd88a5
 
7b97ccd
 
 
 
 
2461d8f
7b97ccd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2461d8f
7b97ccd
 
 
 
7fd88a5
 
 
 
7b97ccd
7fd88a5
7b97ccd
7fd88a5
 
 
 
7b97ccd
 
 
 
7fd88a5
7b97ccd
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
"""Gradio interface for the Hugging Face Space (v21).

Customer-facing page, in Spanish or English (selector at the top, every label
switches): three analysis types (viability / check / market), upload of the
project documents, an optional free-text request, and ONE output — the report.
The report is written by the agent's own skill (``web/analysis.py`` →
``app.build_system_prompt``) on top of the deterministic validators of
``web/routes.py``; without documents and without a request, the page shows the
validators' document alone. A report can be e-mailed after explicit consent
(``web/email_delivery.py``). Nothing about the request is stored; uploads sit
only in Gradio's temporary cache, purged by ``delete_cache``.

Handlers (``on_run``, ``on_send``) are plain functions/generators returning
plain values so they are testable without Gradio installed; :func:`build_demo`
wires them into ``gr.Blocks``. No technical detail (provider, model, library,
region) is ever printed to the customer.
"""

from __future__ import annotations

from typing import Any, Iterator

from web import AGENT_VERSION
from web import analysis, email_delivery, routes, usage_log

try:  # gradio resolves the string annotation ``gr.Request`` (see on_run) in THIS module's globals
    import gradio as gr
except ImportError:  # handlers stay importable/testable without Gradio installed
    gr = None

TITLE = "RailNexus Value — Real Estate & Infrastructure Agent"
LANGUAGES = ["es", "en", "ca"]
ROUTES = ["viability", "check", "market"]

CONSENT_TEXT_EN = (
    "**Consent.** This e-mail delivery is free; in exchange, **the only cost is that your "
    "name and e-mail are sent to a RailNexus address**, exactly as in a normal professional "
    "e-mail exchange — that is the condition for receiving the document by e-mail, and "
    "clicking «Send» accepts it. **Nothing about your analysis, your query or your property "
    "is stored anywhere**: the document is generated in memory, sent to you and discarded."
)

CONSENT_TEXT_CA = (
    "**Consentiment.** Aquest enviament per correu és gratuït; a canvi, **l'únic cost és que "
    "el teu nom i el teu correu s'envien a una adreça de RailNexus**, exactament igual que en "
    "un intercanvi normal de correu professional — aquesta és la condició per rebre el "
    "document per correu, i en prémer «Envia» l'acceptes. **No es desa res sobre la teva "
    "anàlisi, la teva consulta ni la teva propietat enlloc**: el document es genera en "
    "memòria, se t'envia i es descarta."
)

LABELS: dict[str, dict[str, Any]] = {
    "es": {
        "language": "Idioma / Language",
        "intro": "Se utilizan datos públicos en vivo y los documentos que subas; el análisis puede tardar entre 1 y 5 minutos.",
        "route": "Tipo de análisis",
        "routes": {"viability": "Viabilidad — estudio del proyecto, financiación y riesgos",
                   "check": "Comprobación — jurisdicción, documentación, pre-visado (España)",
                   "market": "Mercado — Catastro, suelo y precios (España, en vivo)"},
        "files": "Documentos del proyecto (PDF · DOCX · XLSX · CSV · TXT)",
        "files_note": "Estudios de viabilidad y planes de negocio, memos de inversión y proformas, contratos de arrendamiento y rent rolls, estados financieros y presupuestos, nota simple y due diligence, proyectos para visado y tasaciones, documentación urbanística y de licencias.",
        "request": "¿Qué necesitas?",
        "request_placeholder": "Describe lo que necesitas — o déjalo vacío para el análisis completo del tipo elegido.",
        "description": "Propiedad (dirección o descripción, indicando el país)",
        "description_placeholder": "Edificio de oficinas en Madrid, España",
        "asset_type": "Tipo de activo",
        "project_type": "Tipo de proyecto (pre-visado, España; vacío = ninguno)",
        "colegio": "Colegio", "mode": "Modo", "cee": "Certificado de eficiencia energética ausente",
        "noi": "Ingresos netos de explotación anuales", "debt": "Servicio de deuda anual", "loan": "Préstamo", "value": "Valor de mercado",
        "market_note": "Coordenadas **o** dirección completa (provincia, municipio, vía, número).",
        "lat": "Latitud", "lon": "Longitud", "province": "Provincia", "municipality": "Municipio",
        "street": "Vía", "number": "Número", "radius": "Radio (m)",
        "run": "Ejecutar análisis", "report": "Informe",
        "email_header": "---\n## Recibir este documento por correo",
        "consent": email_delivery.CONSENT_TEXT,
        "name": "Nombre", "email": "Correo electrónico",
        "accept": "He leído y acepto lo anterior", "send": "Enviar",
        "delivery_unavailable": "El envío por correo no está disponible en este momento; puedes copiar el informe directamente.",
        "running": "⏳ Ejecutando los validadores…",
        "writing": "✍️ Redactando el informe…",
        "done": "✅ Análisis completado",
        "degraded": "⚠️ Estado degradado",
        "validator_status": "estado del validador",
        "no_ai": "El análisis de los documentos no está disponible en este momento; se muestra solo el resultado de los validadores.",
        "no_docs": "Sin documentos ni petición: se muestra el resultado de los validadores.",
        "docs_problem": "Documento(s) no legible(s)",
        "truncated": "documento(s) recortado(s) por tamaño",
        "ai_failed": "❌ El informe no se ha podido generar",
        "error": "❌ Error",
        "nothing_stored": "Nada se ha guardado.",
        "assumed": "Jurisdicción no indicada; se ha asumido {country} a partir del documento.",
        "not_given": "Jurisdicción no indicada; el informe la deduce del documento.",
    },
    "en": {
        "language": "Idioma / Language",
        "intro": "Live public data and the documents you upload are used; the analysis can take 1 to 5 minutes.",
        "route": "Analysis type",
        "routes": {"viability": "Viability — project study, financing and risks",
                   "check": "Check — jurisdiction, documentation, pre-visado (Spain)",
                   "market": "Market — Cadastre, land and prices (Spain, live)"},
        "files": "Project documents (PDF · DOCX · XLSX · CSV · TXT)",
        "files_note": "Feasibility studies and business plans, investment memos and pro formas, leases and rent rolls, financial statements and budgets, title reports and due diligence, visado projects and appraisals, planning and licensing documents.",
        "request": "What do you need?",
        "request_placeholder": "Describe what you need — or leave it empty for the full analysis of the chosen type.",
        "description": "Property (address or description, stating the country)",
        "description_placeholder": "Office building in Madrid, Spain",
        "asset_type": "Asset type",
        "project_type": "Project type (pre-visado, Spain; empty = none)",
        "colegio": "College", "mode": "Mode", "cee": "Energy performance certificate missing",
        "noi": "Annual net operating income", "debt": "Annual debt service", "loan": "Loan", "value": "Market value",
        "market_note": "Coordinates **or** full address (province, municipality, street, number).",
        "lat": "Latitude", "lon": "Longitude", "province": "Province", "municipality": "Municipality",
        "street": "Street", "number": "Number", "radius": "Radius (m)",
        "run": "Run analysis", "report": "Report",
        "email_header": "---\n## Receive this document by e-mail",
        "consent": CONSENT_TEXT_EN,
        "name": "Name", "email": "E-mail",
        "accept": "I have read and accept the above", "send": "Send",
        "delivery_unavailable": "E-mail delivery is not available right now; you can copy the report directly.",
        "running": "⏳ Running the validators…",
        "writing": "✍️ Writing the report…",
        "done": "✅ Analysis complete",
        "degraded": "⚠️ Degraded state",
        "validator_status": "validator status",
        "no_ai": "Document analysis is not available right now; only the validators' result is shown.",
        "no_docs": "No documents and no request: the validators' result is shown.",
        "docs_problem": "Unreadable document(s)",
        "truncated": "document(s) cut for size",
        "ai_failed": "❌ The report could not be generated",
        "error": "❌ Error",
        "nothing_stored": "Nothing has been stored.",
        "assumed": "Jurisdiction not stated; {country} was assumed from the document.",
        "not_given": "Jurisdiction not stated; the report infers it from the document.",
    },
    "ca": {
        "language": "Idioma / Language",
        "intro": "S'utilitzen dades públiques en directe i els documents que pugis; l'anàlisi pot trigar entre 1 i 5 minuts.",
        "route": "Tipus d'anàlisi",
        "routes": {"viability": "Viabilitat — estudi del projecte, finançament i riscos",
                   "check": "Comprovació — jurisdicció, documentació, previsat (Espanya)",
                   "market": "Mercat — Cadastre, sòl i preus (Espanya, en directe)"},
        "files": "Documents del projecte (PDF · DOCX · XLSX · CSV · TXT)",
        "files_note": "Estudis de viabilitat i plans de negoci, memoràndums d'inversió i proformes, contractes d'arrendament i rent rolls, estats financers i pressupostos, nota simple i due diligence, projectes per a visat i taxacions, documentació urbanística i de llicències.",
        "request": "Què necessites?",
        "request_placeholder": "Descriu què necessites — o deixa-ho buit per a l'anàlisi completa del tipus triat.",
        "description": "Propietat (adreça o descripció, indicant el país)",
        "description_placeholder": "Edifici d'oficines a Madrid, Espanya",
        "asset_type": "Tipus d'actiu",
        "project_type": "Tipus de projecte (previsat, Espanya; buit = cap)",
        "colegio": "Col·legi", "mode": "Mode", "cee": "Certificat d'eficiència energètica absent",
        "noi": "Ingressos nets d'explotació anuals", "debt": "Servei del deute anual", "loan": "Préstec", "value": "Valor de mercat",
        "market_note": "Coordenades **o** adreça completa (província, municipi, via, número).",
        "lat": "Latitud", "lon": "Longitud", "province": "Província", "municipality": "Municipi",
        "street": "Via", "number": "Número", "radius": "Radi (m)",
        "run": "Executa l'anàlisi", "report": "Informe",
        "email_header": "---\n## Rebre aquest document per correu",
        "consent": CONSENT_TEXT_CA,
        "name": "Nom", "email": "Correu electrònic",
        "accept": "He llegit i accepto el que s'ha exposat", "send": "Envia",
        "delivery_unavailable": "L'enviament per correu no està disponible en aquest moment; pots copiar l'informe directament.",
        "running": "⏳ Executant els validadors…",
        "writing": "✍️ Redactant l'informe…",
        "done": "✅ Anàlisi completada",
        "degraded": "⚠️ Estat degradat",
        "validator_status": "estat del validador",
        "no_ai": "L'anàlisi dels documents no està disponible en aquest moment; només es mostra el resultat dels validadors.",
        "no_docs": "Sense documents ni petició: es mostra el resultat dels validadors.",
        "docs_problem": "Document(s) no llegible(s)",
        "truncated": "document(s) retallat(s) per mida",
        "ai_failed": "❌ No s'ha pogut generar l'informe",
        "error": "❌ Error",
        "nothing_stored": "No s'ha desat res.",
        "assumed": "Jurisdicció no indicada; s'ha assumit {country} a partir del document.",
        "not_given": "Jurisdicció no indicada; l'informe la dedueix del document.",
    },
}


def L(language: str) -> dict[str, Any]:
    return LABELS.get(language, LABELS["es"])


def _status_line(lang: dict, result: routes.RouteResult) -> str:
    """Customer-facing status. Data statuses (market) stay visible and honest; the
    jurisdiction gate never shows as a "degraded" code — the report handles it."""
    if result.route == "market" and result.degraded:
        return f"{lang['degraded']} · {lang['validator_status']}: `{result.status}` — {result.status_note}"
    return lang["done"]


def _number(raw) -> float | None:
    """Optional numeric field: empty, None and 0 all mean "not provided".

    Gradio's Number component renders an untouched field as ``0`` after a label
    update (the language switch), and a zero NOI / loan / coordinate is never a
    real input here — so zero is treated as absent, not computed with.
    """
    if raw in (None, ""):
        return None
    try:
        val = float(raw)
    except (TypeError, ValueError):
        return None
    return None if val == 0 else val


def _run_route(route: str, description: str, asset_type: str, project_type: str, colegio: str,
               mode: str, cee_severity: str, noi, debt_service, loan, value, lat, lon,
               province: str, municipality: str, street: str, number: str, radius,
               language: str) -> routes.RouteResult:
    noi, debt_service, loan, value = (_number(v) for v in (noi, debt_service, loan, value))
    lat, lon = _number(lat), _number(lon)
    if route == "check":
        return routes.run_check(description, asset_type, project_type or "", colegio, mode, cee_severity)
    if route == "viability":
        return routes.run_viability(description, asset_type, noi, debt_service, loan, value)
    if route == "market":
        return routes.run_market(lat, lon, province, municipality, street, number,
                                 int(radius or 1000), 8, language if language in routes.LANGUAGES else "es")
    raise ValueError(f"Unknown route {route!r}")


def _fenced(text: str) -> str:
    return "```text\n" + text.replace("```", "'''") + "\n```"


def on_run(language: str, route: str, files: list | None, request: str, description: str,
           asset_type: str, project_type: str, colegio: str, mode: str, cee_severity: str,
           noi, debt_service, loan, value, lat, lon, province: str, municipality: str,
           street: str, number: str, radius,
           gr_request: gr.Request = None) -> Iterator[tuple[str, str, str]]:
    """Generator: yields (status_md, report_md, document_text) as the analysis progresses.

    ``document_text`` is the plain-text document offered for e-mail; ``report_md``
    is what the page renders. Both are built in memory only. ``gr_request`` is
    injected by Gradio (not a UI input); it feeds only the privacy-safe usage
    record (country / host / channel / client family — never an IP).
    Exactly one usage record is written per call, however the generator ends.
    """
    info: dict[str, Any] = {"state": "ERROR", "cost": 0.0, "passes": 0, "docs": 0}
    try:
        yield from _on_run_inner(info, language, route, files, request, description, asset_type,
                                 project_type, colegio, mode, cee_severity, noi, debt_service, loan,
                                 value, lat, lon, province, municipality, street, number, radius)
    finally:
        usage_log.record_run(route, language, info["state"], info["cost"], info["passes"],
                             info["docs"], gr_request)


def _on_run_inner(info: dict[str, Any], language: str, route: str, files: list | None, request: str,
                  description: str, asset_type: str, project_type: str, colegio: str, mode: str,
                  cee_severity: str, noi, debt_service, loan, value, lat, lon, province: str,
                  municipality: str, street: str, number: str, radius) -> Iterator[tuple[str, str, str]]:
    lang = L(language)
    yield lang["running"], "", ""
    try:
        uploads = analysis.read_uploads(files)
    except OSError as exc:
        yield f"{lang['error']} — {lang['docs_problem']}: {exc}", "", ""
        return
    info["docs"] = len(uploads)
    # Jurisdiction: from the description; else from the documents (the client is only
    # told the assumption); else the validators run uncalibrated and the report infers it.
    given_key, _ = analysis.detect_from_text(description or "")
    jurisdiction_given = bool(given_key)
    assumed_from, validator_description = "", description or ""
    if not jurisdiction_given and uploads:
        docs_preview = analysis.extract_documents(uploads)
        key, country = analysis.detect_from_text("\n".join(d["text"][:20_000] for d in docs_preview if d["text"]))
        if key:
            assumed_from = country
            validator_description = f"{description or ''} ({country})".strip()
    try:
        result = _run_route(route, validator_description, asset_type, project_type, colegio, mode,
                            cee_severity, noi, debt_service, loan, value, lat, lon, province,
                            municipality, street, number, radius, language)
    except Exception as exc:  # noqa: BLE001 — shown to the user, never swallowed
        yield f"{lang['error']} — `{type(exc).__name__}`: {exc}", "", ""
        return
    validators_doc = routes.render_document(result)
    status = _status_line(lang, result)
    if not jurisdiction_given and route != "market":
        status += " · " + (lang["assumed"].format(country=assumed_from) if assumed_from else lang["not_given"])
    if not uploads and not (request or "").strip():
        info["state"] = "VALIDATORS_ONLY"
        yield f"{status} · {lang['no_docs']}", _fenced(validators_doc), validators_doc
        return
    if not analysis.analysis_status()["configured"]:
        info["state"] = analysis.STATE_NOT_CONFIGURED
        yield f"{status} · {lang['no_ai']}", _fenced(validators_doc), validators_doc
        return
    form = {"description": description, "asset_type": asset_type, "project_type": project_type,
            "colegio": colegio if route == "check" else "", "mode": mode if route == "check" else "",
            "cee_severity": cee_severity if route == "check" else "",
            "noi": noi, "debt_service": debt_service, "loan": loan, "value": value,
            "lat": lat, "lon": lon, "province": province, "municipality": municipality,
            "street": street, "number": number, "radius": radius}
    info["state"] = "INTERRUPTED"      # the AI has started; replaced by the real outcome below
    yield f"{status} · {lang['writing']}", "", ""
    report_parts: list[str] = []
    outcome: dict[str, Any] = {}
    for event in analysis.stream_analysis(route, language, request or "", result, form, uploads,
                                          project_type=project_type if route == "check" else "",
                                          colegio=colegio if route == "check" else "",
                                          jurisdiction_given=jurisdiction_given,
                                          assumed_from=assumed_from):
        if event["type"] == "text":
            report_parts.append(event["delta"])
            yield f"{status} · {lang['writing']}", "".join(report_parts), ""
        else:
            outcome = event
            info.update(state=event.get("state", "INTERRUPTED"), cost=event.get("cost_usd") or 0.0,
                        passes=event.get("passes") or 0)
    notes = []
    docs = outcome.get("documents", [])
    if any(d.get("error") for d in docs):
        notes.append(lang["docs_problem"] + ": " + "; ".join(f"{d['name']} — {d['error']}" for d in docs if d.get("error")))
    if any(d.get("truncated") for d in docs):
        notes.append(lang["truncated"])
    note_md = ("\n\n" + " · ".join(notes)) if notes else ""
    if outcome.get("state") == analysis.STATE_ANALYZED:
        # The report IS the deliverable: no validator dump, no JSON, no trailer. The
        # validator results were the model's evidence (user message), not an annex.
        report_md = outcome["analysis"]
        document = (f"RailNexus Value — {lang['routes'][route]}\n"
                    f"{outcome.get('generated_at', '')[:10]}\n\n" + report_md)
        yield status + note_md, report_md, document
        return
    if outcome.get("state") == analysis.STATE_NOT_CONFIGURED:
        yield f"{status} · {lang['no_ai']}" + note_md, _fenced(validators_doc), validators_doc
        return
    if outcome.get("state") in (analysis.STATE_CAPPED, analysis.STATE_EXHAUSTED):
        # Approved fallback text (enterprise plan); the validators' document stays intact.
        yield f"{status}\n\n📮 {outcome.get('message', '')}" + note_md, _fenced(validators_doc), validators_doc
        return
    partial = outcome.get("partial", "")
    detail = outcome.get("message", "")
    body = (partial + "\n\n---\n\n" if partial else "") + _fenced(validators_doc)
    yield f"{lang['ai_failed']} — {detail}" + note_md, body, validators_doc


def on_send(language: str, name: str, email: str, consent: bool, document: str) -> tuple[str, str, str]:
    """E-mail the document; return (result_md, cleared_name, cleared_email)."""
    lang = L(language)
    outcome = email_delivery.send_document(name, email, document, bool(consent))
    state = outcome["state"]
    icon = {"SENT": "✅", "NOT_CONFIGURED": "⛔", "CONSENT_REQUIRED": "☐",
            "INVALID_INPUT": "✏️", "REJECTED_SANDBOX": "🧪", "FAILED": "❌"}.get(state, "•")
    md = f"### {icon} `{state}`\n\n{outcome['message']}\n\n*{lang['nothing_stored']}*"
    if state in ("SENT", "REJECTED_SANDBOX", "FAILED"):
        return md, "", ""          # the request is over: name and e-mail leave the form
    return md, name, email


def delivery_banner(language: str) -> str:
    """Silent when e-mail works; one neutral line (no technical detail) when it does not."""
    return "" if email_delivery.delivery_status()["configured"] else L(language)["delivery_unavailable"]


def build_demo():
    """Create the Gradio Blocks app (imports gradio lazily)."""
    import gradio as gr

    es = LABELS["es"]
    with gr.Blocks(title=TITLE, delete_cache=(300, 600)) as demo:
        gr.Markdown(f"# {TITLE}")
        language = gr.Radio(choices=[("Español", "es"), ("English", "en"), ("Català", "ca")],
                            value="es", label=es["language"])
        intro = gr.Markdown(es["intro"])
        route = gr.Radio(choices=[(v, k) for k, v in es["routes"].items()], value="viability",
                         label=es["route"], elem_id="route-radio")
        files = gr.File(label=es["files"], file_count="multiple", type="filepath",
                        file_types=analysis.SUPPORTED_EXTENSIONS, elem_id="project-files")
        files_note = gr.Markdown(es["files_note"])
        request = gr.Textbox(label=es["request"], placeholder=es["request_placeholder"], lines=3)

        with gr.Group(visible=True) as grp_text:
            description = gr.Textbox(label=es["description"], placeholder=es["description_placeholder"], lines=2)
            asset_type = gr.Dropdown(routes.ASSET_TYPES, value="commercial", label=es["asset_type"])

        with gr.Group(visible=False) as grp_check:
            project_type = gr.Dropdown([""] + routes.PROJECT_TYPES, value="", label=es["project_type"])
            with gr.Row():
                colegio = gr.Dropdown(routes.COLEGIOS, value="COAC", label=es["colegio"])
                mode = gr.Radio(["quick", "full"], value="full", label=es["mode"])
                cee_severity = gr.Radio(["bloqueante", "advertencia"], value="bloqueante", label=es["cee"])

        with gr.Group(visible=True) as grp_viability:
            with gr.Row():
                noi = gr.Number(label=es["noi"], value=None)
                debt_service = gr.Number(label=es["debt"], value=None)
            with gr.Row():
                loan = gr.Number(label=es["loan"], value=None)
                value = gr.Number(label=es["value"], value=None)

        with gr.Group(visible=False) as grp_market:
            market_note = gr.Markdown(es["market_note"])
            with gr.Row():
                lat = gr.Number(label=es["lat"], value=None, precision=6)
                lon = gr.Number(label=es["lon"], value=None, precision=6)
            with gr.Row():
                province = gr.Textbox(label=es["province"])
                municipality = gr.Textbox(label=es["municipality"])
                street = gr.Textbox(label=es["street"])
                number = gr.Textbox(label=es["number"])
            radius = gr.Slider(200, 5000, value=1000, step=100, label=es["radius"])

        run_btn = gr.Button(es["run"], variant="primary")
        status_md = gr.Markdown()
        report_md = gr.Markdown(label=es["report"])
        document_state = gr.State("")

        email_header = gr.Markdown(es["email_header"])
        banner = gr.Markdown(delivery_banner("es"))
        consent_md = gr.Markdown(es["consent"])
        with gr.Row():
            req_name = gr.Textbox(label=es["name"])
            req_email = gr.Textbox(label=es["email"])
        consent = gr.Checkbox(label=es["accept"], value=False)
        send_btn = gr.Button(es["send"], interactive=False)
        send_result = gr.Markdown()

        def _switch_language(selected):
            lang = L(selected)
            return [
                gr.update(label=lang["language"]), gr.update(value=lang["intro"]),
                gr.update(label=lang["route"], choices=[(v, k) for k, v in lang["routes"].items()]),
                gr.update(label=lang["files"]), gr.update(value=lang["files_note"]),
                gr.update(label=lang["request"], placeholder=lang["request_placeholder"]),
                gr.update(label=lang["description"], placeholder=lang["description_placeholder"]),
                gr.update(label=lang["asset_type"]), gr.update(label=lang["project_type"]),
                gr.update(label=lang["colegio"]), gr.update(label=lang["mode"]), gr.update(label=lang["cee"]),
                gr.update(label=lang["noi"]), gr.update(label=lang["debt"]),
                gr.update(label=lang["loan"]), gr.update(label=lang["value"]),
                gr.update(value=lang["market_note"]),
                gr.update(label=lang["lat"]), gr.update(label=lang["lon"]),
                gr.update(label=lang["province"]), gr.update(label=lang["municipality"]),
                gr.update(label=lang["street"]), gr.update(label=lang["number"]),
                gr.update(label=lang["radius"]),
                gr.update(value=lang["run"]), gr.update(label=lang["report"]),
                gr.update(value=lang["email_header"]), gr.update(value=delivery_banner(selected)),
                gr.update(value=lang["consent"]),
                gr.update(label=lang["name"]), gr.update(label=lang["email"]),
                gr.update(label=lang["accept"]), gr.update(value=lang["send"]),
            ]

        language.change(_switch_language, inputs=language, outputs=[
            language, intro, route, files, files_note, request, description, asset_type, project_type,
            colegio, mode, cee_severity, noi, debt_service, loan, value, market_note, lat, lon,
            province, municipality, street, number, radius, run_btn, report_md, email_header,
            banner, consent_md, req_name, req_email, consent, send_btn])

        def _toggle(selected):
            return (gr.update(visible=selected in ("check", "viability")),
                    gr.update(visible=selected == "check"),
                    gr.update(visible=selected == "viability"),
                    gr.update(visible=selected == "market"))

        route.change(_toggle, inputs=route, outputs=[grp_text, grp_check, grp_viability, grp_market])
        consent.change(lambda ok: gr.update(interactive=bool(ok)), inputs=consent, outputs=send_btn)

        run_btn.click(
            on_run,
            inputs=[language, route, files, request, description, asset_type, project_type, colegio,
                    mode, cee_severity, noi, debt_service, loan, value, lat, lon, province,
                    municipality, street, number, radius],
            outputs=[status_md, report_md, document_state],
        )
        send_btn.click(on_send, inputs=[language, req_name, req_email, consent, document_state],
                       outputs=[send_result, req_name, req_email])
    return demo