File size: 4,130 Bytes
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import re
import sys
import time

# Ensure parent directory is in sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import ai_cache
import db
import llm_reviewer
from main import parse_examples_and_constraints_from_text


def backfill_all_problems():
    client = db.get_firestore_client()
    if not client:
        print("Failed to initialize Firestore client.")
        return

    problems_ref = client.collection("problems")
    docs = list(problems_ref.stream())
    total = len(docs)
    print(f"Found {total} problems in Firestore.")

    updated_count = 0
    skipped_count = 0

    for idx, doc in enumerate(docs, start=1):
        prob = doc.to_dict()
        pid = doc.id
        name = prob.get("name", "Unnamed")
        has_ex = bool(prob.get("examples") and isinstance(prob["examples"], list) and len(prob["examples"]) > 0)
        has_co = bool(prob.get("constraints") and ((isinstance(prob["constraints"], list) and len(prob["constraints"]) > 0) or (isinstance(prob["constraints"], str) and prob["constraints"].strip())))

        if has_ex and has_co:
            print(f"[{idx}/{total}] SKIP (Already complete): {name}")
            skipped_count += 1
            continue

        print(f"[{idx}/{total}] Processing: {name}")
        updates = {}
        desc = prob.get("description") or ""

        # Step 1: Parse from description if present
        if (not has_ex or not has_co) and desc:
            clean_desc, parsed_ex, parsed_co = parse_examples_and_constraints_from_text(desc)
            if not has_ex and parsed_ex:
                updates["examples"] = parsed_ex
                has_ex = True
            if not has_co and parsed_co:
                updates["constraints"] = parsed_co
                has_co = True
            if clean_desc and clean_desc != desc:
                updates["description"] = clean_desc
                desc = clean_desc

        # Step 2: If still missing, check cache or fetch from LeetCode
        if not has_ex or not has_co:
            clean_title = re.sub(r'\s*-\s*Method.*$', '', name).strip()
            # Try cache
            data = ai_cache.get_leetcode_problem(clean_title)
            if not data and prob.get("problem_number"):
                data = ai_cache.get_leetcode_problem(f"{prob['problem_number']}. {clean_title}")

            # If not in cache, fetch
            if not data:
                print(f"   Fetching LeetCode data for: {clean_title}")
                try:
                    data = llm_reviewer.fetch_leetcode_problem(clean_title)
                    time.sleep(0.5)  # Be gentle with rate limits
                except Exception as e:
                    print(f"   Error fetching {clean_title}: {e}")
                    data = None

            if data and isinstance(data, dict):
                if not has_ex and data.get("examples"):
                    updates["examples"] = data["examples"]
                    has_ex = True
                if not has_co and data.get("constraints"):
                    updates["constraints"] = data["constraints"]
                    has_co = True
                if not desc and data.get("description"):
                    updates["description"] = data["description"]

        # Normalize constraints to list if string
        if "constraints" in updates and isinstance(updates["constraints"], str):
            updates["constraints"] = [c.strip() for c in updates["constraints"].split('\n') if c.strip()]
        elif "constraints" in prob and isinstance(prob["constraints"], str):
            updates["constraints"] = [c.strip() for c in prob["constraints"].split('\n') if c.strip()]

        if updates:
            print(f"   --> Updating document {pid} with keys: {list(updates.keys())}")
            problems_ref.document(pid).set(updates, merge=True)
            updated_count += 1
        else:
            print(f"   --> No updates found for {name}")

    print(f"\nBackfill completed! Updated: {updated_count}, Already complete: {skipped_count}, Total: {total}")


if __name__ == "__main__":
    backfill_all_problems()