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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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
"""LLM-with-time-series reasoning methods (family ``llm_ts``).

Two concrete classes, all covering T1..T7 per the Method × Task matrix
in the unified-API plan §9:

- :class:`ChatTime`  (``name="chattime"``)  — AAAI 2025 Oral; official repo
                                                ``ForestsKing/ChatTime``.
- :class:`TimeMQA`   (``name="time_mqa"``)  — 2025 LoRA-fine-tuned LLMs on
                                                200K time-series QA pairs;
                                                ``Time-MQA/Qwen-2.5-7B``.

Each class wraps the corresponding LLM-with-TS-reasoning architecture
from :mod:`baselines.llm_ts_reason`. They consume the same per-task
``X`` / ``y`` shapes the unified loader yields (matching :mod:`methods.llm`)
but invoke the architecture-specific time-series tokenizer / patcher /
adapter rather than plain text serialisation of the lookback.

The constructor takes a typed Pydantic config (``ChatTimeConfig``,
``TimeMQAConfig``) plus an injected ``engine``
exposing the OpenAI-compatible
``chat_complete(messages, max_tokens, temperature, top_p) -> str``
protocol (see :mod:`methods._openai_engine`). When ``engine=None`` the
class does NOT eagerly load any model — that is left to the runner who
hands the engine in via DI (consistent with :mod:`methods.llm`).
ChatTime additionally exposes a ``predict(history)`` numeric-forecast
hook that the runner-supplied engine MAY implement; if absent the T1
path falls back to the chat-template completion route.

A ``dry_run=True`` mode is provided for CPU smoke testing: every
inference call is short-circuited to a deterministic placeholder
response and predictions follow the canonical per-task shape so the
runner contract / shape assertions in :mod:`tests.test_method_contract`
can be verified without any GPU, weights, or vLLM engine.

Both classes implement the canonical :class:`methods.base.Method`
contract: ``fit`` (no-op for ZS), ``predict``, ``save`` / ``load`` via
:class:`_HFSaveMixin`, ``default_config``, ``hyperparams``,
``lib_versions``. They consume neither ``meta`` nor any IO; the
``MACROLENS_DETERMINISTIC`` env var seeds python / numpy / torch.

Per-task input / output shapes (mirrors :mod:`methods.llm`):
    T1 : X = (N, lookback, F) np.ndarray  → y_pred (N, horizon) float32.
    T2 : X = pd.DataFrame                  → y_pred (N,) float32.
    T3 : X = pd.DataFrame                  → y_pred long-form
              [ticker, fiscal_year, field, value].
    T4 : X = pd.DataFrame with `lookback`/ `event_type` / `event_description`
              columns                      → y_pred (N,) float32.
    T5 : X = pd.DataFrame                  → y_pred (N,) float32.
    T6 : X = pd.DataFrame                  → y_pred long-form.
    T7 : X = pd.DataFrame                  → y_pred [address, rent, price].
"""

from __future__ import annotations

import json
import logging
import os
import pathlib
import re
from typing import Any

import numpy as np
import pandas as pd

from ._config import (
    ChatTimeConfig,
    LLMTSConfig,
    TimeMQAConfig,
)
from ._openai_engine import DryRunEngine
from ._registry import register
from .base import Method, _HFSaveMixin

logger = logging.getLogger(__name__)


# ── Shared parsing helpers (lifted from baselines.llm_ts_reason) ──────────


_NUM_RE = re.compile(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?")


def _parse_first_number(text: str) -> float | None:
    """Return the first plausible signed/decimal number from ``text``."""
    if not text:
        return None
    cleaned = text.replace(",", "")
    m = _NUM_RE.search(cleaned)
    if not m:
        return None
    try:
        return float(m.group(0))
    except (TypeError, ValueError):
        return None


def _parse_horizon_list(response: str, horizon: int) -> np.ndarray | None:
    """Extract a JSON list of floats representing a forecast trajectory.

    Looks for the first ``[...]`` substring in ``response`` and parses it
    as JSON. Returns a ``(horizon,)`` float32 ndarray, padding with the
    last value when shorter and truncating when longer. Falls back to
    extracting all numeric tokens from the bracketed slice when JSON
    parsing fails. Returns ``None`` on total parse failure.
    """
    if not response:
        return None
    start = response.find("[")
    end = response.rfind("]")
    if start < 0 or end <= start:
        return None
    candidate = response[start : end + 1]
    parsed: list[Any] | None = None
    try:
        loaded = json.loads(candidate)
        if isinstance(loaded, list):
            parsed = loaded
    except json.JSONDecodeError:
        parsed = None
    if parsed is None:
        tokens = _NUM_RE.findall(candidate)
        if not tokens:
            return None
        try:
            parsed = [float(t) for t in tokens]
        except ValueError:
            return None
    vals: list[float] = []
    for v in parsed:
        try:
            vals.append(float(v))
        except (TypeError, ValueError):
            continue
    if not vals:
        return None
    if len(vals) >= horizon:
        out = np.asarray(vals[:horizon], dtype=np.float32)
    else:
        pad = [vals[-1]] * (horizon - len(vals))
        out = np.asarray(vals + pad, dtype=np.float32)
    return out


def _extract_json_object(response: str) -> dict | None:
    """Extract a structured ``{field: value}`` map from an LLM response.

    Two paths:

    1. **JSON object**: legacy support for replies like
       ``{"Revenues": 1000000, "Assets": 5000000}``. Slices from the first
       ``{`` to the last ``}`` and tries ``json.loads``.
    2. **Plain-text key/value**: line-oriented format ``<Field>: <number>``
       which is what current prompts request. Each line is matched by
       regex; numbers may use ``$``, commas, scientific notation. This is
       the natural LLM output mode and avoids JSON parse failures.

    Returns ``None`` if neither path yields any field/value pair.
    """
    if not response:
        return None
    # Path 1: legacy JSON object.
    start = response.find("{")
    end = response.rfind("}")
    if start >= 0 and end > start:
        try:
            j = json.loads(response[start:end + 1])
            if isinstance(j, dict):
                return j
        except json.JSONDecodeError:
            pass
        depth = 0
        for i in range(start, len(response)):
            ch = response[i]
            if ch == "{":
                depth += 1
            elif ch == "}":
                depth -= 1
                if depth == 0:
                    try:
                        j = json.loads(response[start:i + 1])
                        if isinstance(j, dict):
                            return j
                    except json.JSONDecodeError:
                        break
    # Path 2: plain-text "<Field>: <number>" lines (one or many).
    out: dict[str, float] = {}
    line_re = re.compile(
        r"\*?\*?\s*([A-Za-z][A-Za-z0-9_]*)\s*:\s*\$?\s*"
        r"(-?\d[\d,]*(?:\.\d+)?(?:[eE][-+]?\d+)?)"
    )
    for m in line_re.finditer(response):
        field = m.group(1)
        num_str = m.group(2).replace(",", "")
        try:
            out[field] = float(num_str)
        except ValueError:
            continue
    return out or None


def _safe_float(v: Any, default: float = 0.0) -> float:
    """Coerce ``v`` to float, returning ``default`` on missing / non-numeric."""
    if v is None:
        return default
    if isinstance(v, (int, float)) and not (
        isinstance(v, float) and np.isnan(v)
    ):
        return float(v)
    try:
        if pd.isna(v):  # type: ignore[arg-type]
            return default
    except (TypeError, ValueError):
        pass
    try:
        return float(v)
    except (TypeError, ValueError):
        return default


def _seed_from_env(seed: int) -> None:
    """Honor MACROLENS_DETERMINISTIC: seed python/numpy/torch when set."""
    import random

    random.seed(seed)
    np.random.seed(seed)
    os.environ.setdefault("PYTHONHASHSEED", str(seed))
    try:
        import torch

        torch.manual_seed(seed)
        if os.environ.get("MACROLENS_DETERMINISTIC") == "1":
            try:
                torch.use_deterministic_algorithms(True)
            except Exception:
                pass
            try:
                torch.backends.cudnn.deterministic = True  # type: ignore[attr-defined]
            except Exception:
                pass
    except Exception:
        pass


def _find_close_idx_from_array(X: np.ndarray) -> int:
    """Heuristic close-column finder for a (N, L, F) tensor."""
    if X.ndim != 3 or X.shape[2] == 0:
        return 0
    samples = X.reshape(-1, X.shape[2])
    pos_mask = (samples >= 0).all(axis=0)
    if not pos_mask.any():
        return 0
    medians = np.median(np.abs(samples), axis=0)
    candidates = np.where(
        pos_mask & (medians >= 1.0) & (medians <= 5000.0)
    )[0]
    if len(candidates) == 0:
        return 0
    cand_meds = medians[candidates]
    log_cand = np.log10(cand_meds + 1e-9)
    target = np.median(log_cand)
    return int(candidates[np.argmin(np.abs(log_cand - target))])


# ── Task-conditional prompt builders ──────────────────────────────────────


def _t1_prompt(history: np.ndarray, horizon: int, ticker: str = "the stock") -> str:
    """Forecast prompt for T1: emit a horizon-length JSON list of floats."""
    last = float(history[-1]) if len(history) else 0.0
    mean = float(np.mean(history)) if len(history) else 0.0
    std = float(np.std(history)) if len(history) else 0.0
    denom = max(float(history[0]) if len(history) else 1e-2, 1e-2)
    trend = float((history[-1] - history[0]) / denom * 100) if len(history) else 0.0
    last20 = ", ".join(f"{v:.4f}" for v in history[-20:])
    return (
        f"You are a quantitative analyst. Predict the daily closing prices "
        f"of {ticker} for each of the next {horizon} trading days, given:\n"
        f"- Current close: ${last:.2f}\n"
        f"- Past {len(history)} closes: mean=${mean:.2f}, std=${std:.2f}, "
        f"trend={trend:+.1f}%\n"
        f"- Recent close series (last 20 of {len(history)}): [{last20}]\n\n"
        f"Reply with ONLY a JSON array of {horizon} floats, one per future "
        f"trading day, in chronological order:\n"
        f"[float, float, ..., float]"
    )


def _format_macro_snapshot(row: pd.Series) -> str:
    """Render the at-anchor macro snapshot for T2/T5 prompts.

    Mirrors :func:`methods.llm._format_macro_snapshot` so the LLM and
    LLM-TS families show the same four series to the model.
    """
    items: list[str] = []
    series = {
        "10-Year Treasury Yield (DGS10, %)": row.get("fred_DGS10"),
        "Fed Funds Rate (FEDFUNDS, %)": row.get("fred_FEDFUNDS"),
        "VIX (VIXCLS, equity vol)": row.get("fred_VIXCLS"),
        "CPI Headline Level (CPIAUCSL)": row.get("fred_CPIAUCSL"),
    }
    for label, val in series.items():
        if val is None:
            continue
        try:
            if pd.isna(val):
                continue
            items.append(f"{label}: {float(val):,.2f}")
        except (TypeError, ValueError):
            continue
    if not items:
        return "Macro snapshot: not available."
    return "Macro snapshot at anchor date:\n" + "\n".join(items)


def _t2_prompt(row: pd.Series) -> str:
    sector = row.get("sector", "Unknown")
    revenue = _safe_float(row.get("stmt_revenue", 0))
    net_income = _safe_float(row.get("stmt_net_income", 0))
    total_assets = _safe_float(row.get("stmt_total_assets", 0))
    employees = row.get("fullTimeEmployees", "N/A")
    macro = _format_macro_snapshot(row)
    return (
        f"You are a financial analyst. Estimate the total equity market "
        f"capitalization of this company.\n\n"
        f"Sector: {sector}\n"
        f"Revenue: ${revenue:,.0f}\n"
        f"Net Income: ${net_income:,.0f}\n"
        f"Total Assets: ${total_assets:,.0f}\n"
        f"Employees: {employees}\n"
        f"{macro}\n\n"
        f"Reply with ONLY a single number: the estimated market cap in dollars."
    )


def _t5_prompt(row: pd.Series, stmt_cols: list[str]) -> str:
    sector = row.get("sector", "Unknown")
    industry = row.get("industry", "Unknown")
    items = []
    for c in stmt_cols:
        val = row.get(c)
        if pd.notna(val):
            try:
                items.append(f"{c}: ${float(val):,.0f}")
            except (TypeError, ValueError):
                continue
    block = "\n".join(items) if items else "No financial statement data available"
    macro = _format_macro_snapshot(row)
    return (
        f"You are a private equity analyst. Given ONLY financial statement "
        f"data (no market price), estimate the market capitalization of "
        f"this company.\n\n"
        f"Sector: {sector}\n"
        f"Industry: {industry}\n"
        f"{block}\n"
        f"{macro}\n\n"
        f"Reply with ONLY a single number: the estimated market cap in dollars."
    )


_DEFAULT_T3_T6_FIELDS = (
    # MUST match dataloader.load._T3_DENSE_FIELDS exactly (the eval-side
    # canonical field set). Field-name drift between predict-side prompts
    # and eval-side joins produces silent 0% match rates.
    "Revenues, NetIncomeLoss, Assets, Liabilities, StockholdersEquity, "
    "OperatingIncomeLoss, CashAndCashEquivalentsAtCarryingValue, "
    "PropertyPlantAndEquipmentNet, LongTermDebt, "
    "ResearchAndDevelopmentExpense, "
    "NetCashProvidedByUsedInOperatingActivities"
)

# LLMs frequently emit common-English variants of XBRL canonical names
# (Revenue/Revenues, NetIncome/NetIncomeLoss, TotalAssets/Assets, etc.).
# To recover usable predictions instead of forcing predict_failed when
# the canonical name does not appear verbatim, accept these aliases at
# parse time. Lookup is case-insensitive; lowercased keys.
_T3_T6_FIELD_ALIASES: dict[str, list[str]] = {
    "Revenues": [
        "revenues", "revenue", "totalrevenue", "totalrevenues", "sales",
        "totalsales", "stmt_revenue", "netrevenue", "netrevenues",
    ],
    "NetIncomeLoss": [
        "netincomeloss", "netincome", "netearnings", "netprofit",
        "stmt_net_income", "income", "earnings",
    ],
    "Assets": [
        "assets", "totalassets", "stmt_total_assets",
    ],
    "Liabilities": [
        "liabilities", "totalliabilities", "stmt_total_liabilities",
    ],
    "StockholdersEquity": [
        "stockholdersequity", "totalstockholdersequity", "shareholdersequity",
        "totalshareholdersequity", "totalequity", "equity",
        "stmt_total_equity", "bookvalue",
    ],
    "OperatingIncomeLoss": [
        "operatingincomeloss", "operatingincome", "operatingprofit",
        "operatingearnings", "ebit", "stmt_operating_income",
    ],
    "CashAndCashEquivalentsAtCarryingValue": [
        "cashandcashequivalentsatcarryingvalue", "cashandcashequivalents",
        "cashequivalents", "cash", "stmt_cash", "cashandshortterminvestments",
    ],
    "PropertyPlantAndEquipmentNet": [
        "propertyplantandequipmentnet", "propertyplantandequipment",
        "ppe", "netppe", "ppenet", "fixedassets", "stmt_ppe_net",
    ],
    "LongTermDebt": [
        "longtermdebt", "longtermborrowings", "noncurrentdebt",
        "longtermliabilities", "stmt_lt_debt",
    ],
    "ResearchAndDevelopmentExpense": [
        "researchanddevelopmentexpense", "researchanddevelopment", "rd",
        "rnd", "rdexpense", "rndexpense",
    ],
    "NetCashProvidedByUsedInOperatingActivities": [
        "netcashprovidedbyusedinoperatingactivities",
        "operatingcashflow", "cashfromoperations", "operatingcash",
        "netcashoperating", "stmt_operating_cashflow",
    ],
}


def _resolve_canonical_field(parsed: dict, canon_field: str) -> Any:
    """Look up ``canon_field`` in a parsed LLM response dict, accepting
    common-English aliases (case- and underscore-insensitive). Returns
    ``None`` when ``parsed`` is None or no alias matches.
    """
    if parsed is None:
        return None
    aliases = _T3_T6_FIELD_ALIASES.get(canon_field, [canon_field.lower()])
    norm = {
        str(k).lower().replace(" ", "").replace("_", ""): v
        for k, v in parsed.items()
    }
    for alias in [canon_field.lower(), *aliases]:
        key = alias.replace(" ", "").replace("_", "")
        if key in norm:
            return norm[key]
    return None


def _t3_prompt(row: pd.Series, fields_str: str) -> str:
    ticker = str(row.get("ticker", "?"))
    sector = row.get("sector", "Unknown")
    revenue = _safe_float(row.get("stmt_revenue", 0))
    net_income = _safe_float(row.get("stmt_net_income", 0))
    total_assets = _safe_float(row.get("stmt_total_assets", 0))
    total_equity = _safe_float(row.get("stmt_total_equity", 0))
    example_key = fields_str.split(",")[0].strip() or "Revenues"
    return (
        f"You are a financial analyst. Given company fundamentals, predict "
        f"each of the following financial statement fields.\n\n"
        f"Company: {ticker} ({sector})\n"
        f"Revenue: ${revenue:,.0f}\n"
        f"Net Income: ${net_income:,.0f}\n"
        f"Total Assets: ${total_assets:,.0f}\n"
        f"Total Equity: ${total_equity:,.0f}\n\n"
        f"Reply with one line per field, format `<FieldName>: <number>`. "
        f"Use the EXACT field names below (case and spelling must "
        f"match):\n{fields_str}\n\n"
        f"Example:\n"
        f"{example_key}: 1000000\n..."
    )


def _t6_prompt(row: pd.Series, fields_str: str) -> str:
    ticker = str(row.get("ticker", "?"))
    description = row.get(
        "company_description", f"A company with ticker {ticker}"
    )
    sector = row.get("sector", "Unknown")
    industry = row.get("industry", "Unknown")
    example_key = fields_str.split(",")[0].strip() or "Revenues"
    return (
        f"You are a financial analyst. Given this company description: "
        f"'{description}', sector: '{sector}', industry: '{industry}', "
        f"generate plausible values for the following financial fields. "
        f"Use the EXACT field names below (case and spelling must match): "
        f"{fields_str}.\n\n"
        f"Reply with one line per field, format `<FieldName>: <number>`. "
        f"Example:\n"
        f"{example_key}: 1000000\n..."
    )


def _t4_prompt(event_type: str, event_description: str) -> str:
    et_s = str(event_type) if event_type is not None else "unknown"
    ed_s = str(event_description)[:200] if event_description is not None else ""
    return (
        f"You are a quantitative analyst. Predict the percentage return for "
        f"the stock over the next 21 trading days following this "
        f"macroeconomic event.\n\n"
        f"Event type: {et_s}\n"
        f"Description: {ed_s}\n\n"
        f"Reply with ONLY a single number: the predicted return as a "
        f"percentage (e.g., 2.5 for +2.5% or -1.3 for -1.3%)."
    )


def _t7_prompt(row: pd.Series) -> str:
    city = row.get("city", "Unknown")
    state = row.get("state", "Unknown")
    property_type = row.get("property_type", "Unknown")
    sqft = row.get("sqft", "N/A")
    beds = row.get("bedrooms", row.get("beds", "N/A"))
    baths = row.get("bathrooms", row.get("baths", "N/A"))
    year_built = row.get("year_built", "N/A")
    last_sale_date = row.get("last_sale_date", None)
    years_since_last_sale = row.get("years_since_last_sale", None)
    sale_block = ""
    if pd.notna(last_sale_date) and pd.notna(years_since_last_sale):
        try:
            lsd = pd.to_datetime(last_sale_date).strftime("%Y-%m-%d")
            sale_block = (
                f"Last sale: {lsd} "
                f"({float(years_since_last_sale):.1f} years before today). "
            )
        except Exception:
            sale_block = ""
    return (
        f"You are a real estate appraiser estimating value AS OF "
        f"2026-04-11. Given this property: location={city}, {state}, "
        f"type={property_type}, sqft={sqft}, beds={beds}, baths={baths}, "
        f"year_built={year_built}. {sale_block}"
        f"Estimate the monthly rent and sale price.\n\n"
        f"Reply on two lines, dollars only (no $ sign, no commentary):\n"
        f"Rent: <monthly_rent_dollars>\n"
        f"Price: <sale_price_dollars>"
    )


# ── Engine protocol ───────────────────────────────────────────────────────
#
# The shared ``DryRunEngine`` from :mod:`methods._openai_engine` already
# satisfies the chat-complete contract for shape-only smoke tests; we
# re-export it under ``_DryRunEngine`` for backwards-compatibility with
# any local references that still use the legacy name.

_DryRunEngine = DryRunEngine


# ── Base class for all three llm_ts methods ───────────────────────────────


class _LLMTSBase(_HFSaveMixin, Method):
    """Shared scaffolding for ChatTime / Time-MQA.

    Subclasses set ``name`` / ``family`` / ``tasks`` via ``@register`` and
    override ``_default_engine_loader`` if they want eager-load semantics
    when ``engine`` is supplied as ``None`` and ``dry_run`` is ``False``.
    """

    _ALL_TASKS = frozenset({"T1", "T2", "T3", "T4", "T5", "T6", "T7"})

    def __init__(
        self,
        *,
        task: str,
        config: LLMTSConfig | None = None,
        engine: Any = None,
        dry_run: bool = False,
        **kwargs: Any,
    ) -> None:
        if task not in self.tasks:
            raise ValueError(
                f"{type(self).__name__}: task={task!r} not in supported "
                f"set {sorted(self.tasks)}"
            )
        self.task = task
        cfg_cls = self._config_class  # set by @register
        if config is None:
            config = cfg_cls(**kwargs) if kwargs else cfg_cls()
        elif kwargs:
            # Re-validate by merging when both are supplied (rare).
            merged = {**config.model_dump(), **kwargs}
            config = cfg_cls(**merged)
        self.config = config
        # Honor either an explicit ``dry_run`` ctor kwarg OR ``config.dry_run``
        # (the smoke-test path sets the latter via ``cfg.model_copy(...)``).
        self.dry_run = bool(dry_run) or bool(getattr(config, "dry_run", False))
        self._engine = engine if engine is not None else (
            DryRunEngine() if self.dry_run else None
        )
        # Populated post-predict for parse-error tracking.
        self.last_predict_meta: dict[str, Any] = {}
        # Per-task hints settable by the runner (close index, horizon,
        # field-list override). Mirrors :mod:`methods.llm`.
        self._t1_close_idx: int | None = None
        self._t1_horizon: int = 21
        self._t3_t6_fields_str: str = _DEFAULT_T3_T6_FIELDS

    # ── Method contract ──

    @classmethod
    def default_config(cls) -> LLMTSConfig:
        """Return a default-constructed config of the registered class."""
        return cls._config_class()

    def fit(self, X: Any, y: Any, *, seed: int = 42) -> "Method":
        """No-op for zero-shot llm_ts methods (consistent with :mod:`methods.llm`).

        For T1 we still capture ``y.shape[1]`` as the prediction horizon so
        downstream ``predict`` emits matching trajectory lengths (the
        default ``_t1_horizon = 21`` is wrong for the canonical T1 task,
        whose horizon is 252 trading days).
        """
        _seed_from_env(seed)
        if self.task == "T1" and isinstance(y, np.ndarray) and y.ndim == 2:
            self._t1_horizon = int(y.shape[1])
        return self

    def predict(self, X: Any) -> np.ndarray | pd.DataFrame:
        """Dispatch to the per-task predictor for ``self.task``."""
        if self._engine is None and not self.dry_run:
            raise RuntimeError(
                f"{type(self).__name__}.predict called with no engine and "
                "dry_run=False; either inject an engine or set dry_run=True."
            )
        if self.task == "T1":
            return self._predict_t1(X)
        if self.task == "T2":
            return self._predict_t2_t5(X, task="T2")
        if self.task == "T3":
            return self._predict_t3_t6(X, task="T3")
        if self.task == "T4":
            return self._predict_t4(X)
        if self.task == "T5":
            return self._predict_t2_t5(X, task="T5")
        if self.task == "T6":
            return self._predict_t3_t6(X, task="T6")
        if self.task == "T7":
            return self._predict_t7(X)
        raise ValueError(f"Unknown task: {self.task!r}")

    # ── HF-save hooks (ZS — manifest-only) ──

    def _hf_save(self, path: pathlib.Path) -> None:
        # Zero-shot llm_ts methods carry no fit-time state aside from the
        # config + engine reference. The Pydantic config is already
        # serialised via ``manifest.json["hyperparams"]`` by the mixin's
        # save() above, so there's nothing extra to write for ZS.
        # Subclasses that hold non-config state may override.
        return None

    def _hf_load(self, path: pathlib.Path) -> None:
        # Symmetric: no extra artifacts to read for ZS.
        return None

    # ── Engine call ──

    def _call(self, prompt: str, *, max_tokens: int = 256) -> str:
        """Single-prompt inference via the injected engine.

        Subclasses MAY override to use ``engine.predict(numeric_history, ...)``
        for T1 (ChatTime) instead of the natural-language chat-complete
        path. Default contract:
        ``self._engine.chat_complete(messages, max_tokens, ...) -> str``.
        """
        engine = self._engine
        if engine is None:
            raise RuntimeError(
                f"{type(self).__name__}: engine is None and dry_run is False"
            )
        messages = [{"role": "user", "content": prompt}]
        if hasattr(engine, "chat_complete"):
            return str(engine.chat_complete(messages, max_tokens=max_tokens))
        # Backwards-compat hooks for legacy in-process engines.
        if hasattr(engine, "answer"):
            return str(engine.answer(prompt))
        if callable(engine):
            return str(engine(prompt))
        raise RuntimeError(
            f"{type(self).__name__}: injected engine has no .chat_complete() "
            "and is not callable"
        )

    def _call_batch(
        self, prompts: list[str], *, max_tokens: int = 256,
    ) -> list[str]:
        """Batched inference. Default: one HTTP fan-out via the engine's
        ``chat_complete_batch`` (ThreadPoolExecutor inside
        :class:`OpenAIChatEngine`). Falls back to a per-prompt loop when
        the injected engine lacks the batch API. Order is preserved.

        TimeMQA overrides this to wrap each prompt in the authors'
        ``<QUE> ... <ANS>`` template before dispatch and strip ``</END>``
        from each response.
        """
        if not prompts:
            return []
        engine = self._engine
        if engine is None:
            raise RuntimeError(
                f"{type(self).__name__}: engine is None and dry_run is False"
            )
        if hasattr(engine, "chat_complete_batch"):
            batched = [[{"role": "user", "content": p}] for p in prompts]
            return [
                str(r)
                for r in engine.chat_complete_batch(
                    batched, max_tokens=max_tokens,
                )
            ]
        # Fallback to serial single-call loop for legacy engines.
        return [self._call(p, max_tokens=max_tokens) for p in prompts]

    def _call_t1_batch(
        self,
        *,
        prompts: list[str],
        histories: list[np.ndarray],
        horizon: int,
        max_tokens: int = 256,
    ) -> list[str]:
        """Batched T1 inference. Default delegates to :meth:`_call_batch`.

        ChatTime overrides to use ``engine.predict(history)`` (numeric TS
        API) per-row when available, falling back to chat-complete for
        the rows where the numeric path raises. TimeMQA overrides to
        rebuild prompts from ``histories`` using the authors'
        forecasting-question shape (Appendix A.1, Kong et al. 2025).
        """
        del histories, horizon
        return self._call_batch(prompts, max_tokens=max_tokens)

    # ── Per-task predictors ──

    def _predict_t1(self, X: np.ndarray) -> np.ndarray:
        if not isinstance(X, np.ndarray) or X.ndim != 3:
            raise ValueError(
                f"T1 X must be (N, lookback, F) np.ndarray, got "
                f"shape={getattr(X, 'shape', None)} type={type(X).__name__}"
            )
        n, lookback, _n_feats = X.shape
        horizon = int(self._t1_horizon)
        if n == 0:
            self.last_predict_meta = {"task": "T1", "n_attempted": 0,
                                       "n_parse_errors": 0}
            return np.zeros((0, horizon), dtype=np.float32)

        close_idx = (
            self._t1_close_idx
            if self._t1_close_idx is not None
            else _find_close_idx_from_array(X)
        )
        preds = np.full((n, horizon), np.nan, dtype=np.float32)
        # Trajectory output requires more tokens than a single scalar:
        # budget ~12 tokens per horizon step plus brackets/separators.
        max_tokens = max(64, 12 * horizon + 16)
        # Build per-row prompts + histories, then dispatch a single
        # batched HTTP fan-out (the engine's ThreadPoolExecutor handles
        # n_workers concurrency).
        histories: list[np.ndarray] = []
        prompts: list[str] = []
        for i in range(n):
            h = X[i, :, close_idx]
            histories.append(h)
            prompts.append(_t1_prompt(h, horizon))
        responses = self._call_t1_batch(
            prompts=prompts,
            histories=histories,
            horizon=horizon,
            max_tokens=max_tokens,
        )
        unparsed_idx: list[int] = []
        for i, response in enumerate(responses):
            traj = _parse_horizon_list(response, horizon)
            if traj is None:
                unparsed_idx.append(i)
                continue
            preds[i, :] = traj
        if unparsed_idx:
            retry_prompts = [
                prompts[i]
                + f"\n\nIMPORTANT: Reply with EXACTLY {horizon} numbers "
                  "separated by commas, no other text."
                for i in unparsed_idx
            ]
            retry_hists = [histories[i] for i in unparsed_idx]
            retries = self._call_t1_batch(
                prompts=retry_prompts,
                histories=retry_hists,
                horizon=horizon,
                max_tokens=max_tokens,
            )
            still: list[int] = []
            for k, i in enumerate(unparsed_idx):
                traj = _parse_horizon_list(retries[k], horizon)
                if traj is None:
                    still.append(i)
                else:
                    preds[i, :] = traj
            unparsed_idx = still
        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        self.last_predict_meta = {
            "task": "T1", "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
            "horizon_in_prompt": horizon, "close_idx": int(close_idx),
            "lookback": int(lookback),
        }
        return preds

    def _call_t1(
        self,
        prompt: str,
        *,
        history: np.ndarray,
        horizon: int,
        max_tokens: int = 256,
    ) -> str:
        """T1 inference hook — subclasses may use a numeric TS API.

        Default falls back to the natural-language ``_call``. The
        ``max_tokens`` budget is sized for a horizon-length JSON array.
        """
        return self._call(prompt, max_tokens=max_tokens)

    def _predict_t2_t5(self, X: pd.DataFrame, *, task: str) -> np.ndarray:
        if not isinstance(X, pd.DataFrame):
            raise ValueError(
                f"{task} X must be a DataFrame, got type={type(X).__name__}"
            )
        n = len(X)
        if n == 0:
            self.last_predict_meta = {"task": task, "n_attempted": 0,
                                       "n_parse_errors": 0}
            return np.zeros(0, dtype=np.float32)

        if task == "T2":
            prompts = [_t2_prompt(row) for _, row in X.iterrows()]
        else:
            stmt_cols = [c for c in X.columns if c.startswith("stmt_")]
            prompts = [_t5_prompt(row, stmt_cols) for _, row in X.iterrows()]

        responses = self._call_batch(prompts, max_tokens=64)
        preds = np.full(n, np.nan, dtype=np.float64)
        unparsed_idx: list[int] = []
        for i, response in enumerate(responses):
            v = _parse_first_number(response)
            if v is None or v <= 0:
                unparsed_idx.append(i)
                continue
            preds[i] = float(v)
        if unparsed_idx:
            retry_prompts = [
                prompts[i] + "\n\nIMPORTANT: Reply with ONLY a single positive "
                "number (no units, no commas, no currency symbol, no other text)."
                for i in unparsed_idx
            ]
            retries = self._call_batch(retry_prompts, max_tokens=64)
            still: list[int] = []
            for k, i in enumerate(unparsed_idx):
                v = _parse_first_number(retries[k])
                if v is None or v <= 0:
                    still.append(i)
                else:
                    preds[i] = float(v)
            unparsed_idx = still
        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        self.last_predict_meta = {
            "task": task, "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
        }
        return preds

    def _predict_t3_t6(
        self, X: pd.DataFrame, *, task: str,
    ) -> pd.DataFrame:
        if not isinstance(X, pd.DataFrame):
            raise ValueError(
                f"{task} X must be a DataFrame, got type={type(X).__name__}"
            )
        n = len(X)
        if n == 0:
            self.last_predict_meta = {"task": task, "n_attempted": 0,
                                       "n_parse_errors": 0}
            return pd.DataFrame(
                columns=["ticker", "fiscal_year", "field", "pred"]
            )

        fields_str = self._t3_t6_fields_str
        fields_for_row = [
            f.strip() for f in fields_str.split(",") if f.strip()
        ]
        prompts: list[str] = []
        tickers: list[str] = []
        fys: list[Any] = []
        for _, row in X.iterrows():
            tickers.append(str(row.get("ticker", "?")))
            fys.append(row.get("fiscal_year", None))
            prompts.append(
                _t3_prompt(row, fields_str)
                if task == "T3"
                else _t6_prompt(row, fields_str)
            )
        responses = self._call_batch(prompts, max_tokens=1024)
        parsed_per_row = [_extract_json_object(r) for r in responses]
        unparsed_idx = [i for i, p in enumerate(parsed_per_row) if p is None]
        if unparsed_idx:
            retry_prompts = [
                prompts[i]
                + "\n\nIMPORTANT: Reply with EXACTLY one line per field, "
                  "format `<FieldName>: <number>`. No extra commentary."
                for i in unparsed_idx
            ]
            retries = self._call_batch(retry_prompts, max_tokens=1024)
            still: list[int] = []
            for k, i in enumerate(unparsed_idx):
                p = _extract_json_object(retries[k])
                if p is None:
                    still.append(i)
                else:
                    parsed_per_row[i] = p
            unparsed_idx = still
        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        # Canonical fields the eval-side join expects. Only matches against
        # this set count as "valid"; arbitrary keys the LLM invented (e.g.
        # ``Revenue`` for canonical ``Revenues``, ``NetIncome`` for
        # ``NetIncomeLoss``) are filtered out so the predict-side
        # n_valid==0 gate triggers when the LLM cannot produce canonical
        # field names.
        canonical_fields = {f.strip() for f in fields_for_row if f.strip()}
        canonical_lc = {f.lower(): f for f in canonical_fields}

        rows: list[dict[str, Any]] = []
        n_valid = 0
        for i, parsed in enumerate(parsed_per_row):
            ticker = tickers[i]
            fy = fys[i]
            for canon_field in canonical_fields:
                v = _resolve_canonical_field(parsed, canon_field)
                try:
                    pred_val = float(v) if v is not None else np.nan
                except (TypeError, ValueError):
                    pred_val = np.nan
                if not np.isnan(pred_val):
                    n_valid += 1
                rows.append({
                    "ticker": ticker, "fiscal_year": fy,
                    "field": canon_field, "pred": pred_val,
                })
        if n_valid == 0:
            # 0/N valid is a legitimate benchmark measurement for methods that
            # cannot produce the canonical XBRL field schema (ChatTime's
            # 10K-bin numeric tokenizer cannot emit structured text; the
            # chat-fallback path returns ""). Emit the all-NaN frame and let
            # the eval-side fillna(0) -> APE 100% rule score it honestly,
            # rather than converting a real failure into a hard error.
            logger.warning(
                "%s %s predict: 0/%d rows yielded any canonical "
                "(field, value) pair — emitting all-NaN frame; eval will "
                "score as 100%% MAPE.",
                type(self).__name__, task, n,
            )
        # 100% NaN frame — log and pass through; eval-side fillna(0)
        # substitutes 0 per missed field, contributing APE=100% (clipped).
        if not any(
            (r["pred"] is not None) and not (
                isinstance(r["pred"], float) and np.isnan(r["pred"])
            )
            for r in rows
        ):
            logger.warning(
                "%s %s predict: every row NaN; emitting NaN frame — "
                "eval will substitute 0.",
                type(self).__name__, task,
            )

        self.last_predict_meta = {
            "task": task, "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
            "n_valid_field_cells": int(n_valid),
        }
        return pd.DataFrame(
            rows, columns=["ticker", "fiscal_year", "field", "pred"]
        )

    def _predict_t4(self, X: Any) -> np.ndarray:
        # Unified loader yields a DataFrame with `lookback` (object cells),
        # `event_type`, `event_description`. Accept the legacy dict form
        # too for backwards compat with :mod:`methods.llm` callers.
        if isinstance(X, dict):
            event_type = np.asarray(X.get("event_type", []))
            event_desc = np.asarray(X.get("event_description", []))
        elif isinstance(X, pd.DataFrame):
            event_type = (
                X["event_type"].to_numpy()
                if "event_type" in X.columns
                else np.array([])
            )
            event_desc = (
                X["event_description"].to_numpy()
                if "event_description" in X.columns
                else np.array([""] * len(event_type))
            )
        else:
            raise ValueError(
                f"T4 X must be DataFrame or dict, got type={type(X).__name__}"
            )

        n = int(len(event_type))
        if n == 0:
            self.last_predict_meta = {"task": "T4", "n_attempted": 0,
                                       "n_parse_errors": 0}
            return np.zeros(0, dtype=np.float32)
        if len(event_desc) != n:
            raise ValueError(
                f"T4 X: event_type ({len(event_type)}) and "
                f"event_description ({len(event_desc)}) length mismatch."
            )

        prompts = [
            _t4_prompt(event_type[i], event_desc[i]) for i in range(n)
        ]
        responses = self._call_batch(prompts, max_tokens=64)
        preds = np.full(n, np.nan, dtype=np.float32)
        unparsed_idx: list[int] = []
        for i, response in enumerate(responses):
            v = _parse_first_number(response)
            if v is None:
                unparsed_idx.append(i)
                continue
            preds[i] = float(v)
        if unparsed_idx:
            retry_prompts = [
                prompts[i] + "\n\nIMPORTANT: Reply with ONLY a single signed "
                "number (e.g. 2.5 or -1.3). No units, no percent sign, no text."
                for i in unparsed_idx
            ]
            retries = self._call_batch(retry_prompts, max_tokens=64)
            still: list[int] = []
            for k, i in enumerate(unparsed_idx):
                v = _parse_first_number(retries[k])
                if v is None:
                    still.append(i)
                else:
                    preds[i] = float(v)
            unparsed_idx = still
        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        self.last_predict_meta = {
            "task": "T4", "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
        }
        return preds

    def _predict_t7(self, X: pd.DataFrame) -> pd.DataFrame:
        if not isinstance(X, pd.DataFrame):
            raise ValueError(
                f"T7 X must be a DataFrame, got type={type(X).__name__}"
            )
        n = len(X)
        if n == 0:
            self.last_predict_meta = {"task": "T7", "n_attempted": 0,
                                       "n_parse_errors": 0}
            return pd.DataFrame(
                columns=["address", "pred_rent", "pred_price"]
            )

        addrs: list[Any] = []
        prompts: list[str] = []
        for _, row in X.iterrows():
            addrs.append(row.get("address", None))
            prompts.append(_t7_prompt(row))
        responses = self._call_batch(prompts, max_tokens=128)
        parsed_per_row = [_extract_json_object(r) for r in responses]
        unparsed_idx = [i for i, p in enumerate(parsed_per_row) if p is None]
        if unparsed_idx:
            retry_prompts = [
                prompts[i] + "\n\nIMPORTANT: Reply on EXACTLY two lines, "
                "no units / no $ / no commentary:\nRent: <number>\n"
                "Price: <number>"
                for i in unparsed_idx
            ]
            retries = self._call_batch(retry_prompts, max_tokens=128)
            still: list[int] = []
            for k, i in enumerate(unparsed_idx):
                p = _extract_json_object(retries[k])
                if p is None:
                    still.append(i)
                else:
                    parsed_per_row[i] = p
            unparsed_idx = still
        if unparsed_idx:
            logger.warning(
                "%s predict: %d/%d rows unparseable after retry; "
                "emitting NaN — eval-side fillna will substitute 0.",
                type(self).__name__, len(unparsed_idx), n,
            )

        rows: list[dict[str, Any]] = []
        n_valid_rent = 0
        n_valid_price = 0
        for i, parsed in enumerate(parsed_per_row):
            addr = addrs[i]
            if parsed is None:
                rows.append({"address": addr, "pred_rent": np.nan,
                             "pred_price": np.nan})
                continue
            ci = {str(k).lower(): v for k, v in parsed.items()}
            try:
                rent_val = float(ci.get("rent", 0) or 0)
            except (TypeError, ValueError):
                rent_val = np.nan
            try:
                price_val = float(ci.get("price", 0) or 0)
            except (TypeError, ValueError):
                price_val = np.nan
            if not np.isnan(rent_val) and rent_val != 0:
                n_valid_rent += 1
            if not np.isnan(price_val) and price_val != 0:
                n_valid_price += 1
            rows.append({"address": addr, "pred_rent": rent_val,
                         "pred_price": price_val})
        if n_valid_rent == 0 and n_valid_price == 0:
            logger.warning(
                "%s T7 predict: 0/%d rows yielded rent or price — "
                "emitting NaN frame; eval will substitute 0.",
                type(self).__name__, n,
            )

        self.last_predict_meta = {
            "task": "T7", "n_attempted": int(n),
            "n_parse_errors_after_retry": 0,
            "n_valid_rent": int(n_valid_rent),
            "n_valid_price": int(n_valid_price),
        }
        return pd.DataFrame(
            rows, columns=["address", "pred_rent", "pred_price"]
        )


# ── ChatTime ──────────────────────────────────────────────────────────────


@register(
    name="chattime",
    family="llm_ts",
    tasks={"T1", "T2", "T3", "T4", "T5", "T6", "T7"},
    config_class=ChatTimeConfig,
)
class ChatTime(_LLMTSBase):
    """ChatTime (AAAI 2025 Oral) wrapped under the unified Method contract.

    The official ChatTime model exposes both numeric (``predict``) and
    natural-language (``answer``) APIs over the same backbone. We use
    ``predict(history)`` for T1 and ``answer(prompt)`` for T2..T7.

    Engine DI: ``engine`` may be a ``ChatTimeModel`` instance (from
    ``ForestsKing/ChatTime``) exposing ``predict(history)`` and
    ``answer(prompt)``. When ``engine=None`` and ``dry_run=False`` the
    runner is responsible for instantiating the model (vendor clone +
    HF weights at ``ChengsenWang/ChatTime-1-7B-Chat``).
    """

    def _call_t1_batch(
        self,
        *,
        prompts: list[str],
        histories: list[np.ndarray],
        horizon: int,
        max_tokens: int = 256,
    ) -> list[str]:
        """T1 batch: use numeric ``engine.predict(history)`` per-row when
        available; fall back to the chat-complete batched path otherwise.

        Returns one JSON-array-shaped string per row so the unified
        :func:`_parse_horizon_list` parser can consume each entry.
        """
        engine = self._engine
        if (
            engine is not None
            and hasattr(engine, "predict")
            and not self.dry_run
        ):
            outs: list[str] = []
            chat_indices: list[int] = []
            chat_prompts: list[str] = []
            for i, hist in enumerate(histories):
                try:
                    # Pass pred_len to the numeric engine so the authors'
                    # ChatTime.predict() generates the requested horizon
                    # rather than its constructor-time dummy.
                    try:
                        forecast = engine.predict(hist, pred_len=horizon)
                    except TypeError:
                        forecast = engine.predict(hist)
                    if forecast is not None and len(forecast) > 0:
                        vals = [float(v) for v in list(forecast)[:horizon]]
                        if len(vals) < horizon:
                            vals = vals + [vals[-1]] * (horizon - len(vals))
                        outs.append(
                            "[" + ", ".join(f"{v:.4f}" for v in vals) + "]"
                        )
                        continue
                except Exception:
                    pass
                # Numeric path returned empty / raised — defer to
                # chat-complete fallback for this row.
                outs.append("")
                chat_indices.append(i)
                chat_prompts.append(prompts[i])
            if chat_prompts:
                fallback = self._call_batch(
                    chat_prompts, max_tokens=max_tokens,
                )
                for j, i in enumerate(chat_indices):
                    outs[i] = fallback[j]
            return outs
        # No numeric engine — straight chat-complete batch.
        return self._call_batch(prompts, max_tokens=max_tokens)


# ── Time-MQA ──────────────────────────────────────────────────────────────


# Authors' Q&A wrapper — verbatim from the Time-MQA paper, Appendix D
# "Training Data Format" (Kong et al., ACL 2025, p. 29749):
#
#     "We format our question-and-answer pairs using a specifically
#     designed template to clearly separate questions from answers.
#     The template is structured as follows: <QUE> {Question} <ANS>
#     {Answer} </END>. ... In the case of the Qwen model, only
#     <|endoftext|> is added at the end of each sample."
#
# Authors' Q&A *content* style (verbatim, Appendix A.1–A.5, p. 29748):
#   - Question embeds the time series inline as
#     ``The input Time Series are [Time Series Data Points]``.
#   - Answer always begins ``Based on the given information, ...``.
#   - Forecasting answer body is a bracketed list of floats.
#
# We honour the wrapper exactly: the user message we send is
# ``<QUE> {question} <ANS>`` and we ask the model to terminate with
# ``</END>``. Inference is via vLLM ``--enable-lora`` against the
# authors' adapter ``Time-MQA/Qwen-2.5-7B`` over base
# ``Qwen/Qwen2.5-7B-Instruct`` (see :mod:`methods._openai_engine`).
_TIME_MQA_END_TOKEN = "</END>"


def _wrap_time_mqa(question: str) -> str:
    """Wrap an arbitrary task-specific question in the authors' Q&A format.

    The authors trained Qwen-2.5-7B on samples shaped exactly as
    ``<QUE> {Question} <ANS> {Answer} </END>``. At inference we send the
    ``<QUE> ... <ANS>`` prefix verbatim and instruct the model to
    terminate with ``</END>`` (matching the training distribution).
    """
    return (
        f"<QUE> {question} <ANS> Based on the given information, "
    )


def _strip_time_mqa(response: str) -> str:
    """Strip the authors' ``</END>`` terminator + Qwen ``<|endoftext|>``.

    Any of the per-task numeric / JSON parsers already handle a leading
    ``"Based on the given information, ..."`` prefix because they search
    for the first numeric / bracket / brace; we only need to ensure the
    end-of-sample tokens do not corrupt the regex match.
    """
    if not response:
        return response
    out = response
    end_idx = out.find(_TIME_MQA_END_TOKEN)
    if end_idx >= 0:
        out = out[:end_idx]
    out = out.replace("<|endoftext|>", "")
    return out.strip()


def _t1_prompt_time_mqa(
    history: np.ndarray, horizon: int, ticker: str = "the stock"
) -> str:
    """Authors' forecasting-style question for T1 (Appendix A.1, p. 29748).

    Mirrors the training-distribution shape:
        ``... The input Time Series are [v1, v2, ..., vL].
        Please predict the next N time series points given information above.``
    The lookback is serialised as a bracketed comma-separated float list,
    and we ask for the forecast as a bracketed list of ``horizon`` floats
    so :func:`_parse_horizon_list` can consume the response.
    """
    series_str = "[" + ", ".join(f"{float(v):.4f}" for v in history) + "]"
    return (
        f"This dataset records daily closing prices of {ticker}. "
        f"The input Time Series are {series_str}. "
        f"Please predict the next {horizon} time series points given "
        f"information above. Reply with ONLY a list of {horizon} floats "
        f"in the form [v1, v2, ..., v{horizon}]."
    )


@register(
    name="time_mqa",
    family="llm_ts",
    tasks={"T1", "T2", "T3", "T4", "T5", "T6", "T7"},
    config_class=TimeMQAConfig,
)
class TimeMQA(_LLMTSBase):
    """Time-MQA (Kong et al., ACL 2025) under the unified Method contract.

    Time-MQA's Qwen-2.5-7B checkpoint is a LoRA adapter trained on the
    192,843-pair TSQA corpus, with every sample wrapped as
    ``<QUE> {Question} <ANS> {Answer} </END>`` (paper §D, p. 29749).
    The injected engine is the shared OpenAI-compatible vLLM client
    (:class:`OpenAIChatEngine`) served against the authors' adapter via
    ``vllm serve Qwen/Qwen2.5-7B-Instruct --enable-lora --lora-modules
    time_mqa=Time-MQA/Qwen-2.5-7B`` (see :mod:`methods._openai_engine`).

    Faithfulness to the authors' inference distribution
    ---------------------------------------------------
    We honour the authors' published Q&A wrapper exactly: every user
    message is ``<QUE> {question} <ANS> Based on the given
    information,`` and we strip a trailing ``</END>`` from the response
    before parsing. For T1 we additionally adopt the authors'
    forecasting-question shape (Appendix A.1: ``... The input Time
    Series are [...]. Please predict the next N time series points given
    information above.``) so the lookback is serialised in the format
    Qwen-2.5-7B was tuned on.

    Limitation
    ~~~~~~~~~~
    The TSQA corpus does not include MacroLens-style tasks T2/T3/T5/T6/T7
    (market-cap, statement-field, real-estate prediction). For those
    tasks we keep the MacroLens task-specific question content but wrap
    it in the authors' ``<QUE> ... <ANS>`` separators so the model
    operates inside its trained input distribution. Reviewers should
    treat T2/T3/T5/T6/T7 results as the authors' adapter operating on
    out-of-distribution finance/real-estate questions; T1/T4 are the
    closest match to the TSQA forecasting / open-ended-reasoning splits.
    """

    def _call(self, prompt: str, *, max_tokens: int = 256) -> str:
        """Wrap ``prompt`` in the authors' ``<QUE> ... <ANS>`` template."""
        wrapped = _wrap_time_mqa(prompt)
        engine = self._engine
        if engine is None:
            raise RuntimeError(
                f"{type(self).__name__}: engine is None and dry_run is False"
            )
        messages = [{"role": "user", "content": wrapped}]
        if hasattr(engine, "chat_complete"):
            raw = str(engine.chat_complete(messages, max_tokens=max_tokens))
        elif hasattr(engine, "answer"):
            raw = str(engine.answer(wrapped))
        elif callable(engine):
            raw = str(engine(wrapped))
        else:
            raise RuntimeError(
                f"{type(self).__name__}: injected engine has no .chat_complete() "
                "and is not callable"
            )
        return _strip_time_mqa(raw)

    def _call_batch(
        self, prompts: list[str], *, max_tokens: int = 256,
    ) -> list[str]:
        """Batch path with the authors' Q&A wrapper.

        Each prompt is wrapped in ``<QUE> ... <ANS>`` before dispatch and
        each response stripped of ``</END>`` (and Qwen's ``<|endoftext|>``)
        before return. Falls back to per-prompt :meth:`_call` when the
        engine lacks ``chat_complete_batch``.
        """
        if not prompts:
            return []
        engine = self._engine
        if engine is None:
            raise RuntimeError(
                f"{type(self).__name__}: engine is None and dry_run is False"
            )
        wrapped = [_wrap_time_mqa(p) for p in prompts]
        if hasattr(engine, "chat_complete_batch"):
            batched = [[{"role": "user", "content": w}] for w in wrapped]
            raws = [
                str(r)
                for r in engine.chat_complete_batch(
                    batched, max_tokens=max_tokens,
                )
            ]
            return [_strip_time_mqa(r) for r in raws]
        # Legacy engines without batch API: per-prompt loop preserves
        # wrap-and-strip via :meth:`_call`.
        return [self._call(p, max_tokens=max_tokens) for p in prompts]

    def _call_t1_batch(
        self,
        *,
        prompts: list[str],
        histories: list[np.ndarray],
        horizon: int,
        max_tokens: int = 256,
    ) -> list[str]:
        """Override T1 batch to use the authors' forecasting-question shape.

        The default :func:`_t1_prompt`-derived prompts are replaced by
        :func:`_t1_prompt_time_mqa`, which serialises the lookback inline
        as ``[v1, v2, ..., vL]`` and asks for the next ``horizon`` points
        — exactly the shape Qwen-2.5-7B was tuned on for TSQA's
        forecasting split (Appendix A.1, Kong et al. 2025).
        """
        del prompts  # Rebuilt from histories below.
        ts_prompts = [_t1_prompt_time_mqa(h, horizon) for h in histories]
        return self._call_batch(ts_prompts, max_tokens=max_tokens)


__all__ = ["ChatTime", "TimeMQA"]