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
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
"""
Agent-Specific Historical Backfill.

Pulls historical data for the 57-agent registry from sources that support
date-range queries. This extends the observation window from 14 days to
3+ months for the NeurIPS D&B submission.

Backfill sources:
  - Hacker News (Algolia API): full history, date-filterable
  - arXiv:                     papers mentioning agents from last 6 months
  - Stack Overflow:            questions with fromdate/todate (SE API v2.3)
  - GitHub:                    star history, releases, contributor growth
  - PyPI:                      historical download stats (pypistats.org)

Usage:
    python -m collectors.backfill_agents                     # all sources, 3 months
    python -m collectors.backfill_agents --source hn         # HN only
    python -m collectors.backfill_agents --months 4          # go back 4 months
    python -m collectors.backfill_agents --source github     # GitHub history
"""

import sys
import time
import json
import httpx
import logging
import argparse
from datetime import datetime, timedelta, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))
from db.schema import db, get_connection
from collectors.agent_signals import AGENT_REGISTRY

logger = logging.getLogger(__name__)


# ═══════════════════════════════════════════════════════════════════════════════
# Build search terms from agent registry
# ═══════════════════════════════════════════════════════════════════════════════

def _get_agent_search_terms() -> dict[str, list[str]]:
    """Return {search_term: [agent_name, ...]} for all agents."""
    terms = {}
    for agent_name, info in AGENT_REGISTRY.items():
        for term in info.get("search", []):
            terms.setdefault(term, []).append(agent_name)
    return terms


# ═══════════════════════════════════════════════════════════════════════════════
# HN Backfill (Algolia API — supports full history)
# ═══════════════════════════════════════════════════════════════════════════════

def backfill_hn_agents(months: int = 3) -> int:
    """Backfill HN stories mentioning agents from past N months."""
    logger.info("[backfill-agents] HN: going back %d months...", months)
    rows_inserted = 0

    now = datetime.now(timezone.utc)
    start_ts = int((now - timedelta(days=months * 30)).timestamp())
    agent_terms = _get_agent_search_terms()

    with httpx.Client(timeout=30) as client:
        for term, agent_names in agent_terms.items():
            page = 0
            while page < 10:
                params = {
                    "query": term,
                    "tags": "(story,ask_hn,comment)",
                    "numericFilters": f"created_at_i>{start_ts}",
                    "hitsPerPage": 50,
                    "page": page,
                }
                try:
                    r = client.get("https://hn.algolia.com/api/v1/search", params=params)
                    if r.status_code != 200:
                        break
                except Exception:
                    break

                data = r.json()
                hits = data.get("hits", [])
                if not hits:
                    break

                with db() as conn:
                    for hit in hits:
                        story_id = str(hit.get("objectID", ""))
                        created_ts = hit.get("created_at_i")
                        created_at = (datetime.fromtimestamp(created_ts, tz=timezone.utc)
                                      .strftime("%Y-%m-%d %H:%M:%S") if created_ts else None)
                        title = hit.get("title") or hit.get("comment_text", "")[:200] or ""

                        for agent_name in agent_names:
                            try:
                                conn.execute("""
                                    INSERT OR IGNORE INTO hn_signals
                                        (model_slug, story_id, title, score, num_comments,
                                         author, created_at, collected_at)
                                    VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
                                """, (agent_name, story_id, title[:500],
                                      hit.get("points", 0), hit.get("num_comments", 0),
                                      hit.get("author"), created_at))
                                rows_inserted += 1
                            except Exception:
                                pass

                page += 1
                if page >= data.get("nbPages", 0):
                    break
                time.sleep(0.3)

            time.sleep(0.5)

    logger.info("[backfill-agents] HN: inserted %d rows", rows_inserted)
    return rows_inserted


# ═══════════════════════════════════════════════════════════════════════════════
# Stack Overflow Backfill (SE API v2.3 — supports fromdate/todate)
# ═══════════════════════════════════════════════════════════════════════════════

def backfill_stackoverflow_agents(months: int = 3) -> int:
    """Backfill Stack Overflow questions mentioning agents from past N months."""
    logger.info("[backfill-agents] StackOverflow: going back %d months...", months)
    rows_inserted = 0

    now = datetime.now(timezone.utc)
    from_ts = int((now - timedelta(days=months * 30)).timestamp())

    agent_terms = _get_agent_search_terms()

    with httpx.Client(timeout=30) as client:
        for term, agent_names in agent_terms.items():
            params = {
                "order": "desc",
                "sort": "creation",
                "q": term,
                "site": "stackoverflow",
                "pagesize": 50,
                "fromdate": from_ts,
                "filter": "default",
            }
            try:
                r = client.get("https://api.stackexchange.com/2.3/search/advanced", params=params)
                if r.status_code != 200:
                    continue
                data = r.json()
            except Exception:
                continue

            items = data.get("items", [])
            with db() as conn:
                for item in items:
                    q_id = str(item.get("question_id", ""))
                    created_at = datetime.fromtimestamp(
                        item.get("creation_date", 0), tz=timezone.utc
                    ).strftime("%Y-%m-%d %H:%M:%S")

                    for agent_name in agent_names:
                        try:
                            conn.execute("""
                                INSERT OR IGNORE INTO stackoverflow_signals
                                    (model_slug, question_id, title, score, answer_count,
                                     view_count, is_answered, tags, created_at, collected_at)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
                            """, (agent_name, q_id, item.get("title", ""),
                                  item.get("score", 0), item.get("answer_count", 0),
                                  item.get("view_count", 0),
                                  1 if item.get("is_answered") else 0,
                                  ",".join(item.get("tags", [])),
                                  created_at))
                            rows_inserted += 1
                        except Exception:
                            pass

            # SE API has 300 req/day quota — pace conservatively
            time.sleep(2)
            if data.get("quota_remaining", 999) < 10:
                logger.warning("[backfill-agents] SO quota low, stopping")
                break

    logger.info("[backfill-agents] SO: inserted %d rows", rows_inserted)
    return rows_inserted


# ═══════════════════════════════════════════════════════════════════════════════
# GitHub Historical Backfill (star history, releases, contributors over time)
# ═══════════════════════════════════════════════════════════════════════════════

def backfill_github_agents(months: int = 3) -> int:
    """Backfill GitHub release history + contributor growth for agents with repos."""
    logger.info("[backfill-agents] GitHub: going back %d months...", months)
    rows_inserted = 0
    import os
    token = os.environ.get("GITHUB_TOKEN", "")
    headers = {"Accept": "application/vnd.github+json"}
    if token:
        headers["Authorization"] = f"Bearer {token}"

    with httpx.Client(timeout=30, headers=headers) as client:
        for agent_name, info in AGENT_REGISTRY.items():
            repo = info.get("github")
            if not repo:
                continue

            # Get release history
            try:
                r = client.get(f"https://api.github.com/repos/{repo}/releases", params={"per_page": 30})
                if r.status_code == 200:
                    releases = r.json()
                    with db() as conn:
                        for rel in releases:
                            published = rel.get("published_at", "")
                            tag = rel.get("tag_name", "")
                            try:
                                conn.execute("""
                                    INSERT OR IGNORE INTO agent_github_history
                                        (agent_name, event_type, event_data, event_at, collected_at)
                                    VALUES (?, 'release', ?, ?, datetime('now'))
                                """, (agent_name, json.dumps({"tag": tag, "name": rel.get("name", "")}),
                                      published))
                                rows_inserted += 1
                            except Exception:
                                pass
            except Exception:
                pass

            # Get contributor count over time (via contributors endpoint)
            try:
                r = client.get(f"https://api.github.com/repos/{repo}/contributors",
                               params={"per_page": 1, "anon": "false"})
                if r.status_code == 200 and "Link" in r.headers:
                    # Parse last page from Link header to get total contributors
                    link = r.headers["Link"]
                    if 'rel="last"' in link:
                        import re
                        m = re.search(r'page=(\d+)>; rel="last"', link)
                        if m:
                            total = int(m.group(1))
                            with db() as conn:
                                conn.execute("""
                                    INSERT OR IGNORE INTO agent_github_history
                                        (agent_name, event_type, event_data, event_at, collected_at)
                                    VALUES (?, 'contributors_snapshot', ?, datetime('now'), datetime('now'))
                                """, (agent_name, json.dumps({"total": total})))
                                rows_inserted += 1
            except Exception:
                pass

            # Get weekly commit activity (last year)
            try:
                r = client.get(f"https://api.github.com/repos/{repo}/stats/commit_activity")
                if r.status_code == 200:
                    weeks = r.json()
                    if isinstance(weeks, list):
                        with db() as conn:
                            for week in weeks[-months * 4:]:  # last N months of weeks
                                week_ts = week.get("week", 0)
                                week_date = datetime.fromtimestamp(week_ts, tz=timezone.utc).strftime("%Y-%m-%d")
                                try:
                                    conn.execute("""
                                        INSERT OR IGNORE INTO agent_github_history
                                            (agent_name, event_type, event_data, event_at, collected_at)
                                        VALUES (?, 'weekly_commits', ?, ?, datetime('now'))
                                    """, (agent_name, json.dumps({"total": week.get("total", 0)}), week_date))
                                    rows_inserted += 1
                                except Exception:
                                    pass
            except Exception:
                pass

            time.sleep(1)  # GitHub rate limit: 60/hr unauthenticated, 5000/hr with token

    logger.info("[backfill-agents] GitHub: inserted %d rows", rows_inserted)
    return rows_inserted


# ═══════════════════════════════════════════════════════════════════════════════
# PyPI Historical Downloads (pypistats.org API — 180 days of daily data)
# ═══════════════════════════════════════════════════════════════════════════════

def backfill_pypi_agents(months: int = 3) -> int:
    """Backfill PyPI download history for agents with pypi packages."""
    logger.info("[backfill-agents] PyPI: going back %d months...", months)
    rows_inserted = 0

    with httpx.Client(timeout=30) as client:
        for agent_name, info in AGENT_REGISTRY.items():
            pkg = info.get("pypi")
            if not pkg:
                continue

            try:
                r = client.get(f"https://pypistats.org/api/packages/{pkg}/overall",
                               params={"mirrors": "false"})
                if r.status_code != 200:
                    continue
                data = r.json()
            except Exception:
                continue

            cutoff = (datetime.now(timezone.utc) - timedelta(days=months * 30)).strftime("%Y-%m-%d")
            with db() as conn:
                for entry in data.get("data", []):
                    date = entry.get("date", "")
                    if date < cutoff:
                        continue
                    downloads = entry.get("downloads", 0)
                    try:
                        conn.execute("""
                            INSERT OR IGNORE INTO agent_pypi_history
                                (agent_name, date, downloads, collected_at)
                            VALUES (?, ?, ?, datetime('now'))
                        """, (agent_name, date, downloads))
                        rows_inserted += 1
                    except Exception:
                        pass

            time.sleep(1)

    logger.info("[backfill-agents] PyPI: inserted %d rows", rows_inserted)
    return rows_inserted


# ═══════════════════════════════════════════════════════════════════════════════
# arXiv Backfill (papers mentioning agents)
# ═══════════════════════════════════════════════════════════════════════════════

def backfill_arxiv_agents(months: int = 6) -> int:
    """Backfill arXiv papers mentioning agents."""
    import arxiv
    logger.info("[backfill-agents] arXiv: going back %d months...", months)
    rows_inserted = 0
    client = arxiv.Client()

    # Map agent names to arxiv search terms
    ARXIV_AGENT_TERMS = {
        "SWE-bench": ["SWE-agent", "OpenHands", "Devin", "Claude Code"],
        "code agent": ["Claude Code", "Cursor", "Cline", "Aider", "OpenAI Codex"],
        "AI coding assistant": ["GitHub Copilot", "Windsurf", "Tabnine", "Continue"],
        "multi-agent": ["CrewAI", "Microsoft AutoGen", "LangGraph", "MetaGPT"],
        "browser agent": ["Browser Use", "OpenClaw", "Operator", "Multion"],
        "LLM agent evaluation": ["SWE-agent", "OpenHands", "Claude Code"],
        "autonomous agent": ["AutoGPT", "Devin", "Manus", "MetaGPT"],
        "tool use LLM": ["Claude MCP", "OpenAI Agents SDK", "LlamaIndex"],
    }

    for term, agent_names in ARXIV_AGENT_TERMS.items():
        try:
            search = arxiv.Search(
                query=f'all:"{term}"',
                max_results=100,
                sort_by=arxiv.SortCriterion.SubmittedDate,
                sort_order=arxiv.SortOrder.Descending,
            )
            results = list(client.results(search))

            with db() as conn:
                for paper in results:
                    paper_id = paper.entry_id.split("/")[-1]
                    categories = ",".join(paper.categories)
                    published = paper.published.strftime("%Y-%m-%d %H:%M:%S") if paper.published else None

                    for agent_name in agent_names:
                        try:
                            conn.execute("""
                                INSERT OR IGNORE INTO arxiv_signals
                                    (model_slug, paper_id, title, abstract_preview,
                                     categories, authors_count, published_at)
                                VALUES (?, ?, ?, ?, ?, ?, ?)
                            """, (agent_name, paper_id, paper.title,
                                  (paper.summary or "")[:500],
                                  categories, len(paper.authors), published))
                            rows_inserted += 1
                        except Exception:
                            pass

        except Exception as e:
            logger.warning("[backfill-agents] arXiv error for '%s': %s", term, str(e)[:100])

        time.sleep(3)

    logger.info("[backfill-agents] arXiv: inserted %d rows", rows_inserted)
    return rows_inserted


# ═══════════════════════════════════════════════════════════════════════════════
# DB table creation for historical data
# ═══════════════════════════════════════════════════════════════════════════════

def ensure_history_tables():
    """Create tables for historical agent data if they don't exist."""
    with db() as conn:
        conn.execute("""
            CREATE TABLE IF NOT EXISTS agent_github_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                agent_name TEXT NOT NULL,
                event_type TEXT NOT NULL,
                event_data TEXT,
                event_at TEXT,
                collected_at TEXT DEFAULT CURRENT_TIMESTAMP,
                UNIQUE(agent_name, event_type, event_at)
            )
        """)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS agent_pypi_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                agent_name TEXT NOT NULL,
                date TEXT NOT NULL,
                downloads INTEGER DEFAULT 0,
                collected_at TEXT DEFAULT CURRENT_TIMESTAMP,
                UNIQUE(agent_name, date)
            )
        """)


# ═══════════════════════════════════════════════════════════════════════════════
# Main entry point
# ═══════════════════════════════════════════════════════════════════════════════

def run_agent_backfill(sources: list[str] = None, months: int = 3) -> dict:
    """Run agent-specific backfill operations."""
    ensure_history_tables()
    results = {}

    if sources is None:
        sources = ["hn", "so", "github", "pypi", "arxiv"]

    if "hn" in sources:
        results["hn"] = backfill_hn_agents(months)

    if "so" in sources:
        results["so"] = backfill_stackoverflow_agents(months)

    if "github" in sources:
        results["github"] = backfill_github_agents(months)

    if "pypi" in sources:
        results["pypi"] = backfill_pypi_agents(months)

    if "arxiv" in sources:
        results["arxiv"] = backfill_arxiv_agents(min(months, 6))

    return results


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")

    parser = argparse.ArgumentParser(description="Agent-specific historical backfill")
    parser.add_argument("--source", type=str,
                        help="Source to backfill (hn, so, github, pypi, arxiv)")
    parser.add_argument("--months", type=int, default=3,
                        help="Months to go back (default: 3)")
    args = parser.parse_args()

    sources = [args.source] if args.source else None
    results = run_agent_backfill(sources, args.months)

    total = sum(results.values())
    print(f"\n=== Agent Backfill Results ({total} total rows) ===")
    for source, rows in results.items():
        print(f"  {source}: {rows} rows inserted")