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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""LLM inference over Goldenset full_text or per-country PDFs.

For each registered country, reads case inputs from either:
- the `full_text` column of `data/<cc>/Goldenset_*.xlsx`, or
- the PDFs at `data/<cc>/*.pdf`

runs an LLM with the Vorlage coding rules, and appends a CSV of predictions
to `data/<cc>/Goldenset_{country}_{prompt_version}_{full_text|pdf}_{model}.csv`.
Successful rows (by case_id) are skipped; rows with a non-empty `error`
column are retried on the next run.
"""

import argparse
import asyncio
import csv
import json
import logging
import os
import sys
import threading
import time
from collections.abc import Callable
from datetime import date
from pathlib import Path

from dotenv import load_dotenv
from openpyxl import load_workbook

from legex.config import settings
from legex.models.base import Case
from legex.models.classification import Classification
from legex.prompts import PromptPlan, load_plan
from legex.scrapers import SCRAPERS
from legex.utils import (
    classified_csv_path,
    countries_with_goldenset,
    goldenset_path,
    goldenset_sheet,
    load_coding_rules,
    load_goldenset_columns,
    load_isic_categories,
    norm_case_id,
    pdf_paths,
    read_full_text_jsonl,
)

log = logging.getLogger(__name__)

_DATE_FIELD_KEYS: frozenset[str] = frozenset(
    name
    for name, info in Classification.model_fields.items()
    if date in getattr(info.annotation, "__args__", (info.annotation,))
)


def _coerce_json_dates(data: dict) -> None:
    """JSON has no date type; convert strings before pydantic validation."""
    for key in _DATE_FIELD_KEYS:
        if key not in data:
            continue
        val = data[key]
        if isinstance(val, str) and val:
            data[key] = date.fromisoformat(val)


def _parse_classification(content: str) -> Classification:
    """Parse LLM JSON; accept a one-element array when the model returns a list."""
    data = json.loads(content)
    if isinstance(data, list):
        if len(data) != 1 or not isinstance(data[0], dict):
            raise ValueError("expected a JSON object or a one-element array of objects")
        data = data[0]
    _coerce_json_dates(data)
    return Classification.model_validate(data)


class _RequestRateLimiter:
    """Minimum spacing between LLM calls (60 / rpm seconds). None rpm = no limit."""

    def __init__(self, rpm: int | None) -> None:
        self._min_interval = 60.0 / rpm if rpm else 0.0
        self._last_at = 0.0
        self._sync_lock = threading.Lock()
        self._async_lock: asyncio.Lock | None = None

    def acquire(self) -> None:
        if self._min_interval <= 0:
            return
        with self._sync_lock:
            now = time.monotonic()
            wait = self._min_interval - (now - self._last_at)
            if wait > 0:
                time.sleep(wait)
            self._last_at = time.monotonic()

    async def acquire_async(self) -> None:
        if self._min_interval <= 0:
            return
        if self._async_lock is None:
            self._async_lock = asyncio.Lock()
        async with self._async_lock:
            now = time.monotonic()
            wait = self._min_interval - (now - self._last_at)
            if wait > 0:
                await asyncio.sleep(wait)
            self._last_at = time.monotonic()


def inference_output_path(cc: str, prompt_version: str, source: str, model: str) -> Path:
    return classified_csv_path(cc, prompt_version, source, model)


# CSV columns (and GOLDENSET headers) use the alias when one is set,
# e.g. `Currency_dispute_value_nominal` (capital C). The Python attribute
# is the lowercase model field name. These maps move between the two.
_FIELD_TO_COL: dict[str, str] = {
    name: (info.alias or name) for name, info in Classification.model_fields.items()
}
_COL_TO_FIELD: dict[str, str] = {col: field for field, col in _FIELD_TO_COL.items()}


def _output_columns() -> list[str]:
    headers = load_goldenset_columns(settings.template)
    return [h for h in headers if h != "full_text"] + ["model", "error"]


def _read_goldenset_cases(cc: str) -> list[Case]:
    """Pull case_id / link / full_text rows from the GOLDENSET sheet.

    Falls back to data/<cc>/full_text.jsonl (keyed by case_id) when the xlsx
    full_text column is empty or absent, so jurisdictions whose text doesn't
    fit in Excel can still be classified.
    """
    path = goldenset_path(cc)
    wb = load_workbook(path, read_only=True, data_only=True)
    ws = goldenset_sheet(wb)
    rows = ws.iter_rows(values_only=True)
    header = [str(c) if c is not None else "" for c in next(rows)]
    idx = {h.strip().lower(): i for i, h in enumerate(header) if h}
    for required in ("case_id", "link"):
        if required not in idx:
            raise ValueError(f"{path} GOLDENSET sheet missing column {required!r}")
    full_text_idx = idx.get("full_text")
    fallback = read_full_text_jsonl(cc)
    if full_text_idx is None and not fallback:
        raise ValueError(
            f"{path} GOLDENSET sheet has no full_text column and no "
            f"data/{cc}/full_text.jsonl fallback"
        )

    cases: list[Case] = []
    n_from_jsonl = 0
    for row in rows:
        if not any(row):
            continue
        case_id = row[idx["case_id"]]
        link = row[idx["link"]]
        full_text = row[full_text_idx] if full_text_idx is not None else None
        if not full_text and case_id is not None:
            cid_s = str(case_id)
            fb = fallback.get(cid_s) or fallback.get(norm_case_id(cid_s))
            if fb:
                full_text = fb
                n_from_jsonl += 1
        cases.append(
            Case(
                case_id=str(case_id) if case_id is not None else None,
                link=str(link) if link is not None else None,
                jurisdiction=cc,
                full_text=str(full_text) if full_text is not None else None,
            )
        )
    if n_from_jsonl:
        log.info(f"[{cc}] using full_text from full_text.jsonl for {n_from_jsonl} case(s)")
    return cases


def _read_pdf_cases(cc: str) -> list[Case]:
    """One Case per PDF at data/<cc>/*.pdf; case_id = file stem."""
    from pypdf import PdfReader

    cases: list[Case] = []
    for pdf in pdf_paths(cc):
        try:
            reader = PdfReader(str(pdf))
            text = "\n".join((page.extract_text() or "") for page in reader.pages)
        except Exception as e:
            log.warning(f"[{cc}] failed to read {pdf.name}: {type(e).__name__}: {e}")
            text = ""
        cases.append(
            Case(
                case_id=pdf.stem,
                link=str(pdf),
                jurisdiction=cc,
                full_text=text or None,
            )
        )
    return cases


def _read_cases(cc: str, source: str) -> list[Case]:
    if source == "full_text":
        return _read_goldenset_cases(cc)
    return _read_pdf_cases(cc)


def _empty_row(case: Case, model: str, columns: list[str]) -> dict[str, str]:
    row: dict[str, str] = {col: "" for col in columns}
    row["case_id"] = case.case_id or ""
    row["link"] = case.link or ""
    row["model"] = model
    return row


async def _classify_case_single(
    case: Case,
    system_prompt: str,
    model: str,
    columns: list[str],
    limiter: _RequestRateLimiter,
) -> dict[str, str]:
    import litellm

    row = _empty_row(case, model, columns)
    if not case.full_text:
        row["error"] = "no full_text"
        return row

    try:
        await limiter.acquire_async()
        resp = await litellm.acompletion(
            model=model,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": case.full_text},
            ],
            response_format=Classification,
        )
        content = resp["choices"][0]["message"]["content"]
        parsed = _parse_classification(content)
    except Exception as e:
        row["error"] = f"{type(e).__name__}: {e}"
        return row

    extras = [col for col in _FIELD_TO_COL.values() if col not in row]
    if extras:
        row["error"] = f"Classification fields not in GOLDENSET header: {extras}"
        return row
    for field, col in _FIELD_TO_COL.items():
        value = getattr(parsed, field)
        row[col] = "" if value is None else str(value)
    return row


async def _classify_one_column(
    column: str,
    system_prompt: str,
    full_text: str,
    model: str,
    limiter: _RequestRateLimiter,
) -> tuple[str, object | None, str | None]:
    """Return (CSV column, value, error). `column` is the CSV header name
    (alias-aware); we read the corresponding Python attribute off the
    parsed Classification."""
    import litellm

    try:
        await limiter.acquire_async()
        resp = await litellm.acompletion(
            model=model,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": full_text},
            ],
            response_format={"type": "json_object"},
        )
        content = resp["choices"][0]["message"]["content"]
        parsed = _parse_classification(content)
        field = _COL_TO_FIELD.get(column, column)
        return column, getattr(parsed, field), None
    except Exception as e:
        return column, None, f"{column}: {type(e).__name__}: {e}"


async def _classify_case_per_column(
    case: Case,
    column_systems: dict[str, str],
    model: str,
    columns: list[str],
    limiter: _RequestRateLimiter,
) -> dict[str, str]:
    row = _empty_row(case, model, columns)
    if not case.full_text:
        row["error"] = "no full_text"
        return row

    extras = [c for c in column_systems if c not in row]
    if extras:
        row["error"] = f"Per-column prompts target fields not in GOLDENSET header: {extras}"
        return row

    results = await asyncio.gather(
        *(
            _classify_one_column(col, sys_prompt, case.full_text, model, limiter)
            for col, sys_prompt in column_systems.items()
        )
    )
    errors: list[str] = []
    for col, value, err in results:
        if err is not None:
            errors.append(err)
        elif value is not None:
            row[col] = str(value)
    if errors:
        row["error"] = "; ".join(errors)
    return row


class _CsvRowWriter:
    """Append rows to a CSV, flushing after each write."""

    def __init__(self, path: Path, columns: list[str]) -> None:
        path.parent.mkdir(parents=True, exist_ok=True)
        write_header = not path.exists()
        self._file = open(path, "a", encoding="utf-8", newline="")
        self._writer = csv.DictWriter(self._file, fieldnames=columns)
        if write_header:
            self._writer.writeheader()

    def write_row(self, row: dict[str, str]) -> None:
        self._writer.writerow(row)
        self._file.flush()

    def close(self) -> None:
        self._file.close()

    def __enter__(self) -> "_CsvRowWriter":
        return self

    def __exit__(self, *args: object) -> None:
        self.close()


def _classify_cases(
    cases: list[Case],
    plan: PromptPlan,
    model: str,
    columns: list[str],
    limiter: _RequestRateLimiter,
    write_row: Callable[[dict[str, str]], None],
    concurrency: int = 1,
) -> int:
    """Classify cases and stream each result via write_row. Returns success count.

    With concurrency > 1, up to N cases are processed in parallel; the rate
    limiter still gates total request throughput. Rows are written as each
    case finishes, so output order is non-deterministic when concurrency > 1.
    """

    async def run_all() -> int:
        sem = asyncio.Semaphore(max(1, concurrency))

        async def process(case: Case) -> dict[str, str]:
            async with sem:
                if plan.mode == "single":
                    return await _classify_case_single(
                        case, plan.system or "", model, columns, limiter
                    )
                return await _classify_case_per_column(
                    case, plan.column_systems or {}, model, columns, limiter
                )

        ok = 0
        for coro in asyncio.as_completed([process(c) for c in cases]):
            row = await coro
            write_row(row)
            if not row["error"]:
                ok += 1
        return ok

    return asyncio.run(run_all())


def _successful_case_ids(path: Path) -> set[str]:
    if not path.exists():
        return set()
    ids: set[str] = set()
    with open(path, encoding="utf-8", newline="") as f:
        for r in csv.DictReader(f):
            if (r.get("error") or "").strip():
                continue
            cid = (r.get("case_id") or "").strip()
            if cid:
                ids.add(cid)
    return ids


def _drop_case_ids(path: Path, columns: list[str], case_ids: set[str]) -> int:
    """Remove rows for the given case_ids. Returns number of rows removed."""
    if not path.exists() or not case_ids:
        return 0
    with open(path, encoding="utf-8", newline="") as f:
        rows = list(csv.DictReader(f))
    kept = [r for r in rows if (r.get("case_id") or "").strip() not in case_ids]
    removed = len(rows) - len(kept)
    if removed == 0:
        return 0
    with open(path, "w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore")
        writer.writeheader()
        writer.writerows(kept)
    return removed


def classify(
    countries: list[str] | None,
    model: str,
    source: str,
    prompt_version: str,
    limit: int | None,
    rpm: int | None = None,
    concurrency: int = 1,
) -> None:
    rules = load_coding_rules(settings.template)
    isic = load_isic_categories(settings.template)
    columns = _output_columns()
    plan = load_plan(prompt_version, rules, isic)
    limiter = _RequestRateLimiter(rpm)
    if rpm:
        log.info(f"Rate limit: {rpm} requests/min ({limiter._min_interval:.2f}s between calls)")
    if concurrency > 1:
        log.info(f"Concurrency: up to {concurrency} cases in parallel")

    targets = countries or countries_with_goldenset() or list(SCRAPERS)
    for cc in targets:
        if source == "full_text":
            gs = goldenset_path(cc)
            if not gs.exists():
                log.warning(f"[{cc}] missing {gs}, skipping")
                continue
        else:
            if not pdf_paths(cc):
                log.warning(f"[{cc}] no PDFs at {settings.data_dir / cc}/*.pdf, skipping")
                continue

        cases = _read_cases(cc, source)
        if not cases:
            log.info(f"[{cc}] no cases found, skipping")
            continue

        out = inference_output_path(cc, prompt_version, source, model)
        done = _successful_case_ids(out)
        todo = [c for c in cases if (c.case_id or "") not in done]
        if limit is not None:
            todo = todo[:limit]
        if not todo:
            log.info(f"[{cc}] all {len(cases)} cases already classified in {out}, skipping")
            continue

        retry_ids = {c.case_id for c in todo if c.case_id}
        n_removed = _drop_case_ids(out, columns, retry_ids)
        n_new = len(todo) - n_removed
        if n_removed:
            log.info(f"[{cc}] retrying {n_removed} failed case(s), {n_new} new")

        log.info(
            f"[{cc}] classifying {len(todo)} cases ({len(done)} already done) "
            f"in {plan.mode} mode → {out}"
        )
        with _CsvRowWriter(out, columns) as writer:
            n_ok = _classify_cases(
                todo, plan, model, columns, limiter, writer.write_row, concurrency
            )
        log.info(f"[{cc}] classified {n_ok}/{len(todo)}{out}")


def main() -> None:
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[logging.StreamHandler(sys.stderr)],
    )
    load_dotenv(override=True)
    print(f"gemini key {os.environ.get('GEMINI_API_KEY')}")  # sanity check for env var

    parser = argparse.ArgumentParser(
        prog="legex-classify",
        description="Run LLM inference over Goldenset full_text or per-country PDFs.",
    )
    parser.add_argument(
        "--country",
        action="extend",
        nargs="+",
        dest="countries",
        help="Country code (repeatable). Defaults to all registered scrapers.",
    )
    parser.add_argument(
        "--model",
        default="gpt-4o-mini",
        help="litellm model id (e.g. gpt-4o-mini, anthropic/claude-opus-4-7).",
    )
    parser.add_argument(
        "--prompt_version",
        default="v1",
        help="Prompt version under legex/prompts/ (default: v1).",
    )
    parser.add_argument(
        "--limit",
        type=int,
        default=None,
        help="Cap NEW cases per country (useful for cheap dry runs).",
    )
    parser.add_argument(
        "--rpm",
        type=int,
        default=None,
        metavar="N",
        help="Max LLM requests per minute (applies to every completion call).",
    )
    parser.add_argument(
        "--concurrency",
        type=int,
        default=1,
        metavar="N",
        help="Process up to N cases in parallel (default: 1).",
    )
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument(
        "--full_text",
        dest="source",
        action="store_const",
        const="full_text",
        help="Read input from the full_text column of data/<cc>/Goldenset_*.xlsx.",
    )
    source.add_argument(
        "--pdf",
        dest="source",
        action="store_const",
        const="pdf",
        help="Read input from data/<cc>/*.pdf.",
    )
    args = parser.parse_args()
    if args.rpm is not None and args.rpm <= 0:
        parser.error("--rpm must be a positive integer")
    if args.concurrency <= 0:
        parser.error("--concurrency must be a positive integer")

    classify(
        countries=args.countries,
        model=args.model,
        source=args.source,
        prompt_version=args.prompt_version,
        limit=args.limit,
        rpm=args.rpm,
        concurrency=args.concurrency,
    )


if __name__ == "__main__":
    main()