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
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
#!/usr/bin/env python3
import argparse, csv, json, os, random, re, sys, threading, time
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from lxml import etree

BASE = "https://digitallibrary.un.org"
OUT = os.environ.get("UNSC_CORPUS_ROOT", ".")
PROXY_FILE = os.environ.get("UNSC_PROXY_FILE", "proxies.txt")
MARC_NS = {"m": "http://www.loc.gov/MARC21/slim"}

CATEGORIES = {
    "resolutions":             {"p": "191:S/RES",  "pdfs": True},
    "presidential_statements": {"p": "191:S/PRST", "pdfs": True},
    "verbatim_debates":        {"p": "191:S/PV",   "pdfs": True},
    "voting_data":             {"p": '981:"Security Council"', "cc": "Voting Data",
                                "pdfs": False, "voting": True},
}
YEAR_START = 1946
YEAR_END = 2026
RG = 200
REQ_RETRY_PROXIES = 5

_print_lock = threading.Lock()


def log(msg):
    with _print_lock:
        print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)


class ProxyPool:

    MIN_INTERVAL = 0.40
    MAX_INTERVAL = 2.00
    PENALTY = 12.0

    def __init__(self, path):
        self.sessions = []
        for line in open(path):
            line = line.strip()
            if not line:
                continue
            ip, port, user, pw = line.split(":")
            url = f"http://{user}:{pw}@{ip}:{port}"
            s = requests.Session()
            retry = Retry(total=2, backoff_factor=1.0,
                          status_forcelist=[500, 502, 503, 504],
                          allowed_methods=["GET"])
            s.mount("https://", HTTPAdapter(max_retries=retry, pool_maxsize=4))
            s.proxies = {"http": url, "https": url}
            self.sessions.append(s)
        if not self.sessions:
            raise SystemExit("no proxies loaded")
        self._lock = threading.Lock()
        self._next_start = 0.0
        self._penalty_until = 0.0
        self._interval = self.MIN_INTERVAL
        self._ok_streak = 0
        self._n429 = 0
        log(f"loaded {len(self.sessions)} proxies")

    def _throttle(self):
        with self._lock:
            now = time.time()
            start = max(now, self._next_start, self._penalty_until)
            self._next_start = start + self._interval
        wait = start - time.time()
        if wait > 0:
            time.sleep(wait)

    def _on_ok(self):
        with self._lock:
            self._ok_streak += 1
            if self._ok_streak >= 20 and self._interval > self.MIN_INTERVAL:
                self._interval = max(self.MIN_INTERVAL, self._interval * 0.85)
                self._ok_streak = 0

    def _penalize(self):
        with self._lock:
            self._penalty_until = time.time() + self.PENALTY
            self._interval = min(self.MAX_INTERVAL, self._interval * 1.5)
            self._ok_streak = 0
            self._n429 += 1

    def get(self, url, params=None, timeout=90, attempts=8):
        last = None
        for _ in range(attempts):
            self._throttle()
            s = random.choice(self.sessions)
            try:
                r = s.get(url, params=params, timeout=timeout)
                if r.status_code == 429:
                    self._penalize()
                    last = requests.HTTPError("429")
                    continue
                r.raise_for_status()
                self._on_ok()
                return r
            except Exception as e:
                last = e
                continue
        raise last


def sub(field, code):
    el = field.find(f"m:subfield[@code='{code}']", MARC_NS)
    return el.text.strip() if el is not None and el.text else None


def subs(field, code):
    return [e.text.strip() for e in field.findall(f"m:subfield[@code='{code}']", MARC_NS)
            if e.text and e.text.strip()]


def parse_record(rec):
    def cf(tag):
        el = rec.find(f"m:controlfield[@tag='{tag}']", MARC_NS)
        return el.text.strip() if el is not None and el.text else None

    def df(tag):
        return rec.findall(f"m:datafield[@tag='{tag}']", MARC_NS)

    out = {"record_id": cf("001")}
    f191 = df("191")
    out["symbol"] = sub(f191[0], "a") if f191 else None

    f245 = df("245")
    if f245:
        out["title"] = " ".join(filter(None, [sub(f245[0], "a"), sub(f245[0], "b"),
                                               sub(f245[0], "c")])) or None
    f239 = df("239")
    out["descriptive_title"] = sub(f239[0], "a") if f239 else None

    out["date"] = None
    for tag in ("269", "992", "260"):
        f = df(tag)
        if f:
            v = sub(f[0], "c") if tag == "260" else sub(f[0], "a")
            if v:
                out["date"] = v
                break

    out["body"] = [b for f in df("710") for b in [sub(f, "a")] if b] + \
                  [b for f in df("711") for b in [sub(f, "a")] if b]
    out["subjects"] = sorted({s for f in df("650") for s in subs(f, "a")})

    out["agenda"] = []
    for f in df("991"):
        item = {k: sub(f, k) for k in ("a", "b", "c", "d")}
        if any(item.values()):
            out["agenda"].append(item)

    out["related"] = [sub(f, "a") for f in df("993") if sub(f, "a")]
    f791 = df("791")
    out["resolution"] = sub(f791[0], "a") if f791 else None

    f996 = df("996")
    if f996:
        f = f996[0]
        out["vote_outcome"] = sub(f, "a")
        tally = {"yes": sub(f, "b"), "no": sub(f, "c"), "abstain": sub(f, "d"),
                 "nonvoting": sub(f, "e"), "total": sub(f, "f")}
        if any(tally.values()):
            out["vote_tally"] = {k: (int(v) if v and v.isdigit() else v)
                                 for k, v in tally.items()}
    votes = [{"iso": sub(f, "c"), "vote": sub(f, "d"), "country": sub(f, "e")}
             for f in df("967")]
    if votes:
        out["votes"] = votes

    files = {}
    for f in df("856"):
        url = sub(f, "u")
        if not url or not url.lower().endswith(".pdf"):
            continue
        m = re.search(r"-([A-Z]{2})\.pdf$", url)
        files[m.group(1) if m else (sub(f, "y") or "NA")] = url
    out["files"] = files
    return out


def parse_page(xml):
    try:
        root = etree.fromstring(xml)
    except etree.XMLSyntaxError:
        root = etree.fromstring(xml, etree.XMLParser(recover=True))
    return root.findall("m:record", MARC_NS)


def build_params(cfg, p_expr, **extra):
    params = {"p": p_expr}
    if cfg.get("cc"):
        params["cc"] = cfg["cc"]
    params.update(extra)
    return params


def get_count(pool, cfg, p_expr, tries=6):
    for _ in range(tries):
        r = pool.get(f"{BASE}/search", params=build_params(cfg, p_expr, rg=1, ln="en"),
                     timeout=60)
        m = re.search(r"<strong>([0-9,]+)</strong>\s*records found", r.text, re.I)
        if m:
            return int(m.group(1).replace(",", ""))
        if re.search(r"\b0\s+records found", r.text, re.I):
            return 0
        time.sleep(2)
    raise RuntimeError(f"could not read count for query: {p_expr}")


def harvest_year(pool, cat, cfg, mdir, year):
    p_year = f'{cfg["p"]} and year:{year}'
    try:
        yc = get_count(pool, cfg, p_year)
    except Exception as e:
        log(f"[{cat}] {year}: COUNT FAILED ({e})")
        return year, -1, []
    if yc <= 0:
        return year, yc, []
    y_ids, recs_out = set(), []
    jrec, page_i = 1, 0
    while len(y_ids) < yc:
        page_i += 1
        raw = os.path.join(mdir, f"{year}_p{page_i:02d}.xml")
        if os.path.exists(raw) and os.path.getsize(raw) > 200:
            xml = open(raw, "rb").read()
        else:
            r = pool.get(f"{BASE}/search",
                         params=build_params(cfg, p_year, of="xm", rg=RG,
                                             jrec=jrec, so="a", sf="year"),
                         timeout=90)
            xml = r.content
            with open(raw, "wb") as fh:
                fh.write(xml)
        before = len(y_ids)
        for rec in parse_page(xml):
            parsed = parse_record(rec)
            rid = parsed.get("record_id")
            if rid in y_ids:
                continue
            y_ids.add(rid)
            recs_out.append(parsed)
        if len(y_ids) == before:
            break
        jrec += RG
    return year, yc, recs_out


def supplemental_fill(pool, cat, cfg, mdir, seen, records, grand_total):
    sort_keys = [("year", "a"), ("year", "d"), ("title", "a"), ("title", "d"),
                 ("author", "a"), ("author", "d"), ("005", "a"), ("005", "d"),
                 ("245", "a"), ("260", "d")]
    log(f"[{cat}] supplemental fill: have {len(records)}/{grand_total}, paging full set")
    plateau = 0
    round_i = 0
    while len(records) < grand_total and plateau < 1:
        round_i += 1
        before_round = len(records)
        for sf, so in sort_keys:
            for jrec in range(1, grand_total + 1, RG):
                try:
                    r = pool.get(f"{BASE}/search",
                                 params=build_params(cfg, cfg["p"], of="xm", rg=RG,
                                                     jrec=jrec, so=so, sf=sf),
                                 timeout=90)
                except Exception:
                    continue
                raw = os.path.join(mdir, f"supp_{sf}_{so}_{jrec:05d}.xml")
                with open(raw, "wb") as fh:
                    fh.write(r.content)
                for rec in parse_page(r.content):
                    parsed = parse_record(rec)
                    rid = parsed.get("record_id")
                    if rid in seen:
                        continue
                    seen.add(rid)
                    records.append(parsed)
            if len(records) >= grand_total:
                break
        gained = len(records) - before_round
        log(f"[{cat}] supplemental round {round_i}: +{gained} (now {len(records)}/{grand_total})")
        plateau = plateau + 1 if gained == 0 else 0
    return records


def harvest_metadata(pool, cat, cfg, workers):
    cdir = os.path.join(OUT, cat, "metadata")
    mdir = os.path.join(cdir, "marcxml")
    os.makedirs(mdir, exist_ok=True)

    grand_total = get_count(pool, cfg, cfg["p"])
    log(f"[{cat}] grand total reported: {grand_total}")

    years = list(range(YEAR_START, YEAR_END + 1))
    seen, records, year_sum, incomplete = set(), [], 0, []

    with ThreadPoolExecutor(max_workers=workers) as ex:
        futs = {ex.submit(harvest_year, pool, cat, cfg, mdir, y): y for y in years}
        done = 0
        failed_years = []
        for fut in as_completed(futs):
            year, yc, recs = fut.result()
            done += 1
            if yc == -1:
                failed_years.append(year)
                continue
            if yc == 0:
                continue
            year_sum += yc
            got = 0
            for parsed in recs:
                rid = parsed.get("record_id")
                if rid in seen:
                    continue
                seen.add(rid)
                records.append(parsed)
                got += 1
            n_year = len({r["record_id"] for r in recs})
            if n_year != yc:
                incomplete.append((year, n_year, yc))
            if done % 10 == 0 or n_year != yc:
                log(f"[{cat}] {year}: {n_year}/{yc}"
                    f"{' INCOMPLETE' if n_year != yc else ''} "
                    f"(cum {len(records)}, {done}/{len(years)} yrs)")

    if grand_total > 0 and len(records) < grand_total:
        supplemental_fill(pool, cat, cfg, mdir, seen, records, grand_total)

    jsonl_path = os.path.join(cdir, "records.jsonl")
    with open(jsonl_path, "w") as fh:
        for rec in sorted(records, key=lambda r: (r.get("date") or "", r.get("symbol") or "")):
            fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
    log(f"[{cat}] wrote {len(records)} unique records -> {jsonl_path}")
    log(f"[{cat}] sum-of-year-counts={year_sum}, grand_total={grand_total}, "
        f"unique_collected={len(records)}")
    if incomplete:
        log(f"[{cat}] WARNING incomplete years: {incomplete}")
    if failed_years:
        log(f"[{cat}] WARNING count-failed years (rerun to fill): {sorted(failed_years)}")
    return records


def write_voting_csvs(records):
    vdir = os.path.join(OUT, "voting_data")
    os.makedirs(vdir, exist_ok=True)
    with open(os.path.join(vdir, "roll_call.csv"), "w", newline="") as fh:
        w = csv.writer(fh)
        w.writerow(["record_id", "resolution", "date", "country_iso", "country", "vote"])
        for rec in records:
            for v in rec.get("votes", []):
                w.writerow([rec.get("record_id"), rec.get("resolution"),
                            rec.get("date"), v.get("iso"), v.get("country"), v.get("vote")])
    with open(os.path.join(vdir, "summary.csv"), "w", newline="") as fh:
        w = csv.writer(fh)
        w.writerow(["record_id", "resolution", "date", "yes", "no", "abstain",
                    "nonvoting", "total", "outcome", "title"])
        for rec in records:
            t = rec.get("vote_tally") or {}
            w.writerow([rec.get("record_id"), rec.get("resolution"), rec.get("date"),
                        t.get("yes"), t.get("no"), t.get("abstain"), t.get("nonvoting"),
                        t.get("total"), rec.get("vote_outcome"), rec.get("title")])
    log("[voting_data] wrote roll_call.csv & summary.csv")


def safe_name(symbol):
    return re.sub(r"[^A-Za-z0-9.]+", "_", symbol).strip("_")


def download_pdfs(pool, cat, records, langs, workers):
    pdir = os.path.join(OUT, cat, "pdfs")
    os.makedirs(pdir, exist_ok=True)
    err_path = os.path.join(OUT, cat, "pdf_errors.log")

    tasks = []
    for rec in records:
        sym = rec.get("symbol") or rec.get("record_id")
        for lang in langs:
            url = (rec.get("files") or {}).get(lang)
            if not url:
                continue
            fpath = os.path.join(pdir, f"{safe_name(sym)}-{lang}.pdf")
            if os.path.exists(fpath) and os.path.getsize(fpath) > 1000:
                continue
            tasks.append((sym, lang, url, fpath))

    log(f"[{cat}] {len(tasks)} PDFs to fetch ({len(langs)} lang(s))")
    counts = {"got": 0, "fail": 0}
    lock = threading.Lock()

    def one(task):
        sym, lang, url, fpath = task
        try:
            r = pool.get(url, timeout=120)
            if not r.content.startswith(b"%PDF"):
                raise ValueError("not a PDF")
            with open(fpath, "wb") as fh:
                fh.write(r.content)
            with lock:
                counts["got"] += 1
                if counts["got"] % 250 == 0:
                    log(f"[{cat}] pdf {counts['got']}/{len(tasks)}")
        except Exception as e:
            with lock:
                counts["fail"] += 1
            with open(err_path, "a") as fh:
                fh.write(f"{sym}\t{lang}\t{url}\t{e}\n")

    with ThreadPoolExecutor(max_workers=workers) as ex:
        list(ex.map(one, tasks))
    log(f"[{cat}] PDFs done: got {counts['got']}, failed {counts['fail']}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--only", nargs="*", choices=list(CATEGORIES))
    ap.add_argument("--langs", nargs="*", default=["EN"])
    ap.add_argument("--no-pdfs", action="store_true")
    ap.add_argument("--meta-only", action="store_true")
    ap.add_argument("--pdfs-only", action="store_true",
                    help="skip metadata harvest; download PDFs from existing records.jsonl")
    ap.add_argument("--workers", type=int, default=6)
    args = ap.parse_args()

    cats = args.only or list(CATEGORIES)
    pool = ProxyPool(PROXY_FILE)
    os.makedirs(OUT, exist_ok=True)

    for cat in cats:
        cfg = CATEGORIES[cat]
        log(f"===== {cat} =====")
        if args.pdfs_only:
            path = os.path.join(OUT, cat, "metadata", "records.jsonl")
            records = [json.loads(l) for l in open(path)] if os.path.exists(path) else []
            log(f"[{cat}] loaded {len(records)} records from {path}")
        else:
            records = harvest_metadata(pool, cat, cfg, args.workers)
            if cfg.get("voting"):
                write_voting_csvs(records)
        if cfg.get("pdfs") and not args.no_pdfs and not args.meta_only:
            download_pdfs(pool, cat, records, args.langs, args.workers)

    log("ALL DONE")


if __name__ == "__main__":
    main()