File size: 28,012 Bytes
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ba6fa3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ffaa98
4ba6fa3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
4ba6fa3
 
 
 
 
 
 
27c9320
4ba6fa3
 
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
"""
Comparator: dispatches per-field rules from rules.py (TIE Logics.docx).
"""
from __future__ import annotations
import os
import re
from datetime import datetime
from typing import Any, Dict, List, Optional
import openpyxl
from openpyxl.styles import Alignment, Font, PatternFill, Border, Side
from openpyxl.chart import PieChart, Reference
from openpyxl.worksheet.datavalidation import DataValidation

from tie_loader import TIE, _norm
import rules
import insights
import i18n
import translator as _translator


def read_ai_file(path):
    """Open AI Excel even if it's locked by Excel/OneDrive — copy to temp first."""
    import shutil, tempfile
    src_path = path
    try:
        wb = openpyxl.load_workbook(src_path, data_only=True, read_only=True)
    except (PermissionError, OSError):
        # File may be open in Excel or sync-locked. Copy bytes to a temp file.
        tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
        tmp.close()
        try:
            with open(src_path, "rb") as fsrc, open(tmp.name, "wb") as fdst:
                shutil.copyfileobj(fsrc, fdst)
        except Exception:
            # Last-ditch: shutil.copyfile (may also fail). Re-raise after.
            shutil.copyfile(src_path, tmp.name)
        wb = openpyxl.load_workbook(tmp.name, data_only=True, read_only=True)
    if "ProjectData" not in wb.sheetnames:
        raise ValueError("AI file missing 'ProjectData' tab")
    ws = wb["ProjectData"]
    headers = None
    rows = []
    for i, row in enumerate(ws.iter_rows(values_only=True)):
        if i == 0:
            headers = [str(h or "").strip() for h in row]; continue
        if not row or not row[0]: continue
        rows.append(dict(zip(headers, row)))
    return rows


def _canon(s):
    if s is None: return ""
    return re.sub(r"\s+", " ", str(s)).strip().lower()


# Quick heuristic for free-text language detection. Returns 'en', 'es',
# 'pt', or 'unknown'. Used to decide whether the Transformed Value
# column should be machine-translated to match BNA's language.
_PT_STOPS = re.compile(
    r"\b(?:o|a|os|as|do|da|dos|das|um|uma|de|para|com|por|que|n[aã]o|ser|est[aã]|s[aã]o|mais|seu|sua|seus|suas|projeto|obras|opera[çc][aã]o)\b",
    re.IGNORECASE)
_ES_STOPS = re.compile(
    r"\b(?:el|la|los|las|del|al|de|en|para|con|por|que|no|este|esta|sus|ser|est[áa]|son|m[aá]s|su|proyecto|obras|operaci[oó]n)\b",
    re.IGNORECASE)
_EN_STOPS = re.compile(
    r"\b(?:the|of|to|and|in|for|is|on|with|that|this|by|as|will|are|its|project|works|operation)\b",
    re.IGNORECASE)


def _detect_text_lang(text):
    if not text:
        return "unknown"
    s = str(text).strip()
    if len(s) < 40:
        return "unknown"
    low = s.lower()
    # Strong signal from accented characters that English doesn't use.
    pt_char_hits = sum(low.count(c) for c in "çãõẽâô")
    es_char_hits = sum(low.count(c) for c in "ñ¿¡")
    # Stopword counts as the main vote.
    pt = len(_PT_STOPS.findall(low))
    es = len(_ES_STOPS.findall(low))
    en = len(_EN_STOPS.findall(low))
    # Accent characters bias the verdict toward PT/ES.
    pt_score = pt + 3 * pt_char_hits
    es_score = es + 3 * es_char_hits
    if pt_score >= en and pt_score > es_score and pt_score >= 2:
        return "pt"
    if es_score >= en and es_score > pt_score and es_score >= 2:
        return "es"
    if en >= 2:
        return "en"
    return "unknown"


def _combine_ai_rows(ai_rows):
    """Multi-row handling: when the AI Excel has several rows for the
    same Field name, merge them into a single row. Values are joined
    with ', '. Date is the most recent (max). Other metadata picks the
    first non-empty value."""
    merged = {}
    order = []
    for r in ai_rows:
        field = r.get("Field") or ""
        key = re.sub(r"\s+", " ", str(field)).strip().lower()
        if key not in merged:
            merged[key] = dict(r)
            order.append(key)
            continue
        cur = merged[key]
        # Combine value
        v_old = "" if cur.get("Value") in (None, "") else str(cur.get("Value")).strip()
        v_new = "" if r.get("Value") in (None, "") else str(r.get("Value")).strip()
        if v_new and v_new not in v_old.split(", "):
            cur["Value"] = (v_old + ", " + v_new) if v_old else v_new
        # Pick the most recent date
        from datetime import datetime as _dt
        def _dparse(s):
            if s is None: return None
            if isinstance(s, _dt): return s
            try:
                from rules import parse_date as _pd
                return _pd(s)
            except Exception:
                return None
        d_old = _dparse(cur.get("Date"))
        d_new = _dparse(r.get("Date"))
        if d_new and (d_old is None or d_new > d_old):
            cur["Date"] = r.get("Date")
        # First non-empty fill for other metadata
        for fk in ("Notes", "Confidence", "Strategy", "Source", "Source URL"):
            if not cur.get(fk) and r.get(fk):
                cur[fk] = r.get(fk)
    return [merged[k] for k in order]


# Fields that are metadata, not data points — they appear in the output
# for context (so the researcher can see what URL was scraped) but they
# are NEVER compared against BNA. Verdict is left blank and they are
# excluded from the Match / Differ tallies.
_NO_COMPARE_FIELDS = {
    "project permalink", "permalink",
    "permalink del proyecto", "permalink do projeto",
    "slug",
}


def build_comparison_rows(ai_rows, bna_fields, tie, lang="es", debug_dir=None):
    out = []
    trace_lines = []
    ai_rows = _combine_ai_rows(ai_rows)
    for r in ai_rows:
        ai_field = r.get("Field") or ""
        ai_value = r.get("Value")
        ai_notes = r.get("Notes")
        ai_conf = r.get("Confidence")
        ai_strategy = r.get("Strategy")
        ai_source = r.get("Source")
        ai_source_url = r.get("Source URL")
        ai_date = r.get("Date")

        # Skip comparison for permalink-style metadata rows — they exist
        # in the AI sheet purely so the batch app can navigate to the BNA
        # URL. Show them in the output unchanged, with no verdict.
        if str(ai_field).strip().lower() in _NO_COMPARE_FIELDS:
            out.append({
                "ai_field": ai_field, "ai_value": ai_value, "ai_notes": ai_notes,
                "ai_confidence": ai_conf, "ai_strategy": ai_strategy,
                "ai_source": ai_source, "ai_source_url": ai_source_url,
                "ai_date": ai_date,
                "transformed": "" if ai_value is None else str(ai_value),
                "bna_value": "", "match": "", "reco": "",
            })
            continue

        bna_data = _find_bna(ai_field, bna_fields, tie)
        transformed, bna_value, match, reco = rules.apply_rule(
            ai_field, ai_value, ai_date, bna_data, tie, lang,
            bna_fields=bna_fields,
        )
        # Per-row trace for diagnostics
        try:
            bna_repr = repr(bna_data)[:300]
            trace_lines.append(
                f"AI_FIELD={ai_field!r}\n"
                f"  AI_VALUE={ai_value!r}\n"
                f"  AI_DATE={ai_date!r}\n"
                f"  BNA_DATA_FOUND={bna_repr}\n"
                f"  TRANSFORMED={transformed!r}\n"
                f"  BNA_VALUE_OUT={bna_value!r}\n"
                f"  MATCH={match}\n"
                f"  RECO={reco!r}\n"
            )
        except Exception: pass
        out.append({
            "ai_field": ai_field, "ai_value": ai_value, "ai_notes": ai_notes,
            "ai_confidence": ai_conf, "ai_strategy": ai_strategy,
            "ai_source": ai_source, "ai_source_url": ai_source_url,
            "ai_date": ai_date, "transformed": transformed,
            "bna_value": bna_value, "match": match, "reco": reco,
        })
    # Persist trace
    if debug_dir:
        try:
            import os as _os
            _os.makedirs(debug_dir, exist_ok=True)
            with open(_os.path.join(debug_dir, "comparison_trace.txt"),
                     "w", encoding="utf-8") as f:
                f.write("\n".join(trace_lines))
        except Exception: pass
    return out


FIELD_TO_BNA_LABELS = {
    "owner company": ["Owner", "Owners"],
    "concessionaire / operator company": ["Concessionaire/operator", "Concessionaire", "Operator"],
    "contractor company": ["Main contractor", "Contractor", "EPC", "EPCM"],
    "engineering company": ["Engineering"],
    "equipment / technology provider": ["Technology provider", "Equipment"],
    "consultancy company": ["Consultancy"],
    "project name": ["Project Name", "Name"],
    "project stage": ["Current stage", "Stage"],
    "project description": ["Description", "Descripción", "Descrição"],
    "description": ["Description", "Descripción", "Descrição"],
    "descripción": ["Description", "Descripción", "Descrição"],
    "descripción del proyecto": ["Description", "Descripción", "Descrição"],
    "descrição": ["Description", "Descripción", "Descrição"],
    "descrição do projeto": ["Description", "Descripción", "Descrição"],
    "property type": ["Property Type"],
    "development type": ["Development type"],
    "capex": ["Capex", "CAPEX"],
    "lifespan": ["Lifespan"],
    "project type": ["Project Type", "Project Type and capacity"],
    "milestones": ["Milestones"],
    "announcement date": ["Project Announced"],
    "completion_end of construction date": ["End of Construction"],
    "construction start date": ["Start of Construction"],
    "contractor tendering start date": ["Start of Main Contractor Tendering"],
    "detailed engineering start date": ["Start of Detailed Engineering"],
    "environmental approval date": ["Environmental and Social Approval"],
    "environmental approval": ["Environmental and Social Approval"],
    "environmental and social approval": ["Environmental and Social Approval"],
    "environmental and social approval date": ["Environmental and Social Approval"],
    "operations start date": ["Start of Operation"],
    "tendering start date": ["Start of Main Contractor Tendering"],
    "latitude and longitude": ["Coordinates", "Latitude", "Longitude"],
    "main works description": ["Principal works", "Principal Works"],
    "project documentation": [],
    "project manager": ["Project Manager"],
    "purchasing manager": ["Purchasing Manager"],
    "engineering manager": ["Engineering Manager"],
    "capacity": ["Capacity"],
}


def _find_bna(ai_field, bna_fields, tie=None):
    if not bna_fields: return None
    key = re.sub(r"\s+", " ", str(ai_field).strip().lower())

    # Contact roles — preferred path: Contacts radio + Area chip click harvested
    # names directly from the page into "manager::<Role>".
    if key in ("project manager", "purchasing manager", "engineering manager"):
        target_role = {"project manager": "Project Manager",
                       "purchasing manager": "Purchasing Manager",
                       "engineering manager": "Engineering Manager"}[key]
        names = []
        v = bna_fields.get(f"manager::{target_role}")
        if v:
            names = list(v) if isinstance(v, list) else [str(v)]
        # Fallback to legacy bracket-position path
        if not names and tie is not None:
            for k, val in bna_fields.items():
                if not str(k).startswith("position::"): continue
                bracket = str(k)[len("position::"):]
                mapped = tie.map_project_position_to_role(bracket)
                if mapped and _canon(mapped) == _canon(target_role):
                    if isinstance(val, list): names.extend(val)
                    else: names.append(str(val))
        # de-dupe preserving order
        seen = set(); uniq = []
        for n in names:
            if n and n not in seen:
                seen.add(n); uniq.append(n)
        return uniq if uniq else None

    # Company fields — preferred path: scraper harvested chip-by-chip into
    # "company::<Chip>" using the editable TIE 'Company Chip Mapping' sheet.
    if tie is not None:
        chip = tie.map_ai_company_field_to_chip(ai_field)
        if chip:
            v = bna_fields.get(f"company::{chip}")
            if v is not None:
                return v if isinstance(v, list) else [str(v)]
            # Fallback: any key whose canon equals the chip label.
            for k, val in bna_fields.items():
                if _canon(k) == _canon(chip):
                    return val if isinstance(val, list) else [str(val)]
            return None  # Chip configured but not harvested → Not Available

    candidates = FIELD_TO_BNA_LABELS.get(key, [ai_field])
    # Pass 1: exact canonical match — strongest signal, used everywhere.
    for cand in candidates:
        for k, v in bna_fields.items():
            if _canon(k) == _canon(cand): return v
    # Pass 2: substring fallback — but only for fields where it's safe.
    # 'capacity' substring matches 'project type and capacity' which is the
    # raw merged blob, not real capacity. For capacity, instead derive the
    # numeric portion from the merged 'Project Type and capacity' field
    # so the comparison never shows 'Not available' when the value is in
    # fact present on the BNA page.
    if key == "capacity":
        blob_labels = ("project type and capacity",
                       "tipo y capacidad del proyecto",
                       "tipo de proyecto y capacidad",
                       "tipo e capacidade do projeto",
                       "tipo de projeto e capacidade")
        for k, v in bna_fields.items():
            kc = _canon(k)
            if kc in blob_labels:
                blob = str(v or "")
                # Capture digit run + lowercase unit phrase. Stops at the
                # next Capitalized word (BNA blob format is
                # "<TypeName> <number><lower-unit> <TypeName>...").
                m = re.search(
                    r"(\d[\d\.\,]*(?:\s+[a-zà-ÿ/]+){1,10})",
                    blob)
                if m:
                    return m.group(1).strip()
        return None
    for cand in candidates:
        for k, v in bna_fields.items():
            if _canon(cand) and _canon(cand) in _canon(k): return v
    return None


HEADER_FILL = PatternFill("solid", fgColor="1F4E78")
HEADER_FONT = Font(color="FFFFFF", bold=True)
MATCH_FILL = PatternFill("solid", fgColor="C6EFCE")     # green
DIFFER_FILL = PatternFill("solid", fgColor="FFEB9C")    # yellow
PENDING_FILL = PatternFill("solid", fgColor="DDDDDD")   # grey - Missing on Both
MISSING_AI_FILL = PatternFill("solid", fgColor="D6E9FE")   # light blue - Missing on AI
STALE_FILL = PatternFill("solid", fgColor="E9D5FF")     # light purple - Stale AI
THIN = Side(style="thin", color="BFBFBF")
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)

NOT_AVAILABLE = {"es": "No disponible", "en": "Not Available", "pt": "Não disponível"}


def _style_header(ws, n):
    for col in range(1, n + 1):
        c = ws.cell(row=1, column=col)
        c.fill = HEADER_FILL; c.font = HEADER_FONT
        c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
        c.border = BORDER
    ws.row_dimensions[1].height = 28


def _autosize(ws, max_w=60):
    """Compute column widths. Skips MergedCell instances which lack
    .column / .column_letter (openpyxl quirk when a sheet contains
    merged ranges, e.g. our BNA Project URL banner)."""
    from openpyxl.utils import get_column_letter
    for col_idx in range(1, ws.max_column + 1):
        letter = get_column_letter(col_idx)
        longest = 0
        for r in range(1, ws.max_row + 1):
            cell = ws.cell(row=r, column=col_idx)
            # Skip MergedCells (no own value past the anchor)
            if cell.__class__.__name__ == "MergedCell":
                continue
            v = "" if cell.value is None else str(cell.value)
            lines = v.splitlines() if v else [""]
            cur = max((len(s) for s in lines), default=0)
            longest = max(longest, min(max_w, cur))
        ws.column_dimensions[letter].width = max(12, min(longest + 2, max_w))


def write_comparison_sheet(ws, rows, lang, tie, reco_only=False, project_url=None):
    base_headers = i18n.HEADERS[lang]
    extra_headers = i18n.RECO_HEADERS_EXTRA[lang] if reco_only else []
    headers = list(base_headers) + list(extra_headers)
    # Row 1: BNA Project URL banner (merged across the whole header range)
    url_label = "BNA Project URL: " + (project_url or "")
    cell = ws.cell(row=1, column=1, value=url_label)
    cell.font = Font(bold=True, color="1F4E78")
    cell.alignment = Alignment(horizontal="left", vertical="center")
    if len(headers) > 1:
        ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(headers))
    ws.row_dimensions[1].height = 22
    # Row 2: column headers
    for i, h in enumerate(headers, 1):
        ws.cell(row=2, column=i, value=h)
    for col in range(1, len(headers) + 1):
        c = ws.cell(row=2, column=col)
        c.fill = HEADER_FILL; c.font = HEADER_FONT
        c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
        c.border = BORDER
    ws.row_dimensions[2].height = 28
    r = 3
    na = NOT_AVAILABLE.get(lang, "Not Available")
    # Recommendations sheet includes rows that need researcher attention:
    # 'Differ' (value mismatch) and 'Stale AI' (AI value older than BNA review).
    # Visual fill colors keep the two categories separate (yellow vs purple).
    RECO_VERDICTS = {"Differ", "Stale AI"}
    for row in rows:
        if reco_only and row["match"] not in RECO_VERDICTS:
            continue
        match_tr = i18n.MATCH_LABEL[lang].get(row["match"], row["match"])
        bna_disp = row["bna_value"] if row["bna_value"] not in (None, "", []) else na
        # Translate BNA enum values (Property Type / Development Type /
        # Project Type / Stage) into the selected output language.
        try:
            if lang != "en" and bna_disp and bna_disp != na:
                bna_disp = i18n.translate_bna_value(row["ai_field"], bna_disp, lang, tie)
        except Exception:
            pass
        # Capacity unit-phrase translation (numbers stay; unit text is
        # localised). Applies to both BNA value and AI Transformed.
        try:
            if lang != "en" and _norm(row.get("ai_field")) == "capacity":
                if bna_disp and bna_disp != na:
                    bna_disp = i18n.translate_capacity_value(bna_disp, lang, tie)
                # Capacity transformed gets handled below via transformed_disp
        except Exception:
            pass
        # Translate the AI field name into the selected output language so
        # the 'Campo IA / AI Field' column reads natively.
        try:
            field_disp = i18n.translate_field_name(row["ai_field"], lang, tie) if tie else row["ai_field"]
        except Exception:
            field_disp = row["ai_field"]
        # Translate AI-side placeholder phrases first (Not Publicly Disclosed,
        # Not yet disclosed, N/A, TBD, ...) into the selected output language.
        def _tr_ph(v):
            try:
                return i18n.translate_placeholder(v, lang) if lang != "en" else v
            except Exception:
                return v
        ai_value_disp = _tr_ph(row["ai_value"])
        ai_source_disp = _tr_ph(row.get("ai_source") or "")
        ai_date_disp = _tr_ph(row.get("ai_date") or "")
        ai_source_url_disp = _tr_ph(row.get("ai_source_url") or "")
        transformed_disp = row["transformed"]
        # Capacity transformed translation
        try:
            if lang != "en" and _norm(row.get("ai_field")) == "capacity" and transformed_disp:
                transformed_disp = i18n.translate_capacity_value(
                    transformed_disp, lang, tie)
        except Exception:
            pass
        # Free-text fields (Description / Milestones / Principal Works /
        # Main Works) — language-aware Transformed Value.
        #
        # Translation rule, per row:
        #   1. If the BNA Value came back in the target language (because
        #      BNA editors translated it for this project), translate the
        #      Transformed Value to the target language too — both
        #      columns line up and the comparison is apples-to-apples.
        #   2. If the BNA Value came back in English (because BNA has no
        #      translated version stored for this project), KEEP the
        #      Transformed Value as the AI's original English. That way
        #      the comparison is between Agentic's original English text
        #      and BNA's English text — same language, fair comparison.
        #
        # This sidesteps the previous problem where translating the
        # Transformed Value to ES/PT while BNA Value stayed English made
        # the two columns un-comparable visually.
        try:
            ai_field_norm = _norm(row.get("ai_field"))
            FREE_TEXT_FIELDS = {
                "project description", "description",
                "descripción", "descripción del proyecto",
                "descrição", "descrição do projeto",
                "milestones", "hitos", "marcos",
                "main works description",
                "descripción de obras principales",
                "descrição das obras principais",
                "principal works", "obras principales", "obras principais",
            }
            if lang != "en" and ai_field_norm in FREE_TEXT_FIELDS:
                bna_text_lang = _detect_text_lang(str(bna_disp or ""))
                # Only translate the Transformed Value when BNA actually
                # returned the target language. Otherwise leave it as the
                # AI's original English so it aligns with the BNA column.
                if (bna_text_lang == lang
                        and transformed_disp
                        and len(str(transformed_disp).strip()) > 20):
                    transformed_disp = _translator.translate_free_text(
                        str(transformed_disp), src_lang="en",
                        dst_lang=lang, tie=tie)
        except Exception:
            pass
        # "Recommendation" column now carries the Match/Differ verdict directly.
        values = [
            field_disp, ai_value_disp, transformed_disp,
            bna_disp, match_tr,
            ai_source_disp,
            ai_source_url_disp,
            ai_date_disp,
        ]
        if reco_only:
            values.extend(["", ""])  # Researcher Command, Researcher's Remark
        for col, v in enumerate(values, 1):
            cell = ws.cell(row=r, column=col, value=v)
            cell.alignment = Alignment(wrap_text=True, vertical="top")
            cell.border = BORDER
        verdict = row["match"]
        if verdict == "Match":
            fill = MATCH_FILL
        elif verdict == "Missing on Both":
            fill = PENDING_FILL
        elif verdict == "Missing on AI":
            fill = MISSING_AI_FILL
        elif verdict == "Stale AI":
            fill = STALE_FILL
        else:
            fill = DIFFER_FILL
        for col in range(1, len(headers) + 1):
            ws.cell(row=r, column=col).fill = fill
        r += 1
    # Researcher Command dropdown on Recommendations sheet only
    if reco_only and r > 3:
        opts = ",".join(i18n.VALID_OPTIONS[lang])
        dv = DataValidation(type="list", formula1=f'"{opts}"', allow_blank=True,
                            showDropDown=False)
        dv.error = "Select Valid or Invalid"
        dv.errorTitle = "Invalid value"
        dv.prompt = "Pick Valid or Invalid"
        dv.promptTitle = "Researcher Command"
        col_letter = ws.cell(row=2, column=len(base_headers) + 1).column_letter
        dv.add(f"{col_letter}3:{col_letter}{r-1}")
        ws.add_data_validation(dv)
    _autosize(ws)
    ws.freeze_panes = "A3"


def write_insights_sheet(ws, metrics, lang):
    headers = i18n.INSIGHTS_HEADERS[lang]
    for i, h in enumerate(headers, 1):
        ws.cell(row=1, column=i, value=h)
    _style_header(ws, len(headers))
    table = insights.to_table(metrics, lang=lang)
    for i, (k, v) in enumerate(table, 2):
        ws.cell(row=i, column=1, value=k).border = BORDER
        ws.cell(row=i, column=2, value=v).border = BORDER
    # Append verdict legend so leadership reading the Insights sheet has a
    # reference for what each verdict means.
    r = len(table) + 3
    ws.cell(row=r, column=1, value=i18n.VERDICT_LEGEND_TITLE.get(lang, "Verdict legend")).font = Font(bold=True)
    r += 1
    for line in i18n.VERDICT_LEGEND_ITEMS.get(lang, []):
        ws.cell(row=r, column=1, value=line).alignment = Alignment(wrap_text=True)
        ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=2)
        r += 1
    _autosize(ws, max_w=80)


def write_log_sheet(ws, log_lines, lang):
    headers = i18n.LOG_HEADERS[lang]
    for i, h in enumerate(headers, 1):
        ws.cell(row=1, column=i, value=h)
    _style_header(ws, len(headers))
    r = 2
    for line in log_lines:
        parts = line.split("|", 2)
        if len(parts) == 3: ts, lvl, msg = parts
        else: ts, lvl, msg = datetime.now().isoformat(timespec="seconds"), "INFO", line
        ws.cell(row=r, column=1, value=ts.strip()).border = BORDER
        ws.cell(row=r, column=2, value=lvl.strip()).border = BORDER
        ws.cell(row=r, column=3, value=msg.strip()).border = BORDER
        ws.cell(row=r, column=3).alignment = Alignment(wrap_text=True, vertical="top")
        r += 1
    _autosize(ws, max_w=80)
    ws.freeze_panes = "A2"


SHEET_TITLES = {
    "comparison": {"es": "Comparación", "en": "Comparison", "pt": "Comparação"},
    "insights":   {"es": "Indicadores", "en": "Insights", "pt": "Indicadores"},
    "log":        {"es": "Registro", "en": "Log", "pt": "Registro"},
    "reco":       {"es": "Recomendaciones", "en": "Recommendations", "pt": "Recomendações"},
}


def _long(p):
    """Prefix the Windows long-path marker on `p` so paths over the
    legacy 260-char MAX_PATH limit are accepted. No-op on non-Windows
    or paths already carrying the marker."""
    if os.name == "nt" and not str(p).startswith("\\\\?\\"):
        return "\\\\?\\" + os.path.abspath(p)
    return p


def _safe_save(wb, path):
    # Ensure parent dir exists (defensive — gui.py creates it but if a
    # long-path issue trims it, recreate here).
    try:
        os.makedirs(_long(os.path.dirname(path)), exist_ok=True)
    except Exception:
        pass
    try:
        wb.save(_long(path)); return path
    except PermissionError:
        stem, ext = os.path.splitext(path)
        alt = f"{stem}_{datetime.now().strftime('%H%M%S')}{ext}"
        wb.save(_long(alt)); return alt


def write_outputs(out_dir, rows, log_lines, metrics, tie,
                  base_name="BNA_Comparison", languages=("es",), project_url=None):
    os.makedirs(_long(out_dir), exist_ok=True)
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    written = []
    for lang in languages:
        wb = openpyxl.Workbook(); ws = wb.active
        ws.title = SHEET_TITLES["comparison"][lang]
        write_comparison_sheet(ws, rows, lang, tie, project_url=project_url)
        ws_ins = wb.create_sheet(SHEET_TITLES["insights"][lang])
        p1 = os.path.join(out_dir, f"{base_name}_Comparison_{lang}_{ts}.xlsx")
        written.append(_safe_save(wb, p1))

        wb = openpyxl.Workbook(); ws = wb.active
        write_log_sheet(ws, log_lines, lang)
        p2 = os.path.join(out_dir, f"{base_name}_Log_{lang}_{ts}.xlsx")
        written.append(_safe_save(wb, p2))

        wb = openpyxl.Workbook(); ws = wb.active
        ws.title = SHEET_TITLES["reco"][lang]
        write_comparison_sheet(ws, rows, lang, tie, reco_only=True, project_url=project_url)
        p3 = os.path.join(out_dir, f"{base_name}_Recommendations_{lang}_{ts}.xlsx")
        written.append(_safe_save(wb, p3))
    return written