File size: 11,512 Bytes
aaa634c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
import streamlit as st
from google.oauth2 import service_account
from googleapiclient.discovery import build
import db

def get_secret(key):
    import os
    # Try environment variables first
    env_val = os.environ.get(key.upper()) or os.environ.get(key)
    if env_val:
        if key == "gcp_service_account" or (isinstance(env_val, str) and env_val.strip().startswith("{")):
            import json
            try:
                return json.loads(env_val)
            except Exception:
                pass
        return env_val

    try:
        # Try Streamlit secrets first
        if hasattr(st, "secrets") and st.secrets and key in st.secrets:
            return st.secrets[key]
    except Exception:
        pass
    
    # Fallback to loading from toml directly
    import toml
    try:
        secrets_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".streamlit", "secrets.toml")
        if os.path.exists(secrets_path):
            data = toml.load(secrets_path)
            if key in data:
                return data[key]
    except Exception:
        pass
    return None

def get_credentials():
    creds_dict = get_secret("gcp_service_account")
    if not creds_dict:
        raise KeyError("gcp_service_account not found in secrets")
    return service_account.Credentials.from_service_account_info(
        dict(creds_dict),
        scopes=[
            'https://www.googleapis.com/auth/drive.readonly',
            'https://www.googleapis.com/auth/documents.readonly'
        ]
    )

def extract_text_from_elements(elements):
    text = ""
    for value in elements:
        if 'paragraph' in value:
            for elem in value.get('paragraph', {}).get('elements', []):
                if 'textRun' in elem:
                    text += elem.get('textRun', {}).get('content', '')
    return text

def parse_problem_body(problem_name, body):
    # Match headers like "Method 1:" or "Method 2 (Two Pointers):"
    method_matches = list(re.finditer(r'Method\s*(\d+)(?:\s*\(([^)]+)\))?:', body, re.IGNORECASE))
    
    difficulty = "Medium"
    diff_match = re.search(r'^\s*(Easy|Medium|Hard)\b', body, re.IGNORECASE | re.MULTILINE)
    if diff_match:
        difficulty = diff_match.group(1).capitalize()
        
    methods = []
    
    # Extract description text: everything before the first Method match or Time Complexity line, excluding the difficulty word.
    desc_raw = ""
    if method_matches:
        desc_raw = body[:method_matches[0].start()]
    else:
        time_match = re.search(r'Time\s+Complexity:\s*([^\n\r]+)', body, re.IGNORECASE)
        if time_match:
            desc_raw = body[:time_match.start()]
        else:
            desc_raw = body
            
    description = re.sub(r'^\s*(Easy|Medium|Hard)\b', '', desc_raw, flags=re.IGNORECASE | re.MULTILINE).strip()
    
    if not method_matches:
        # Fallback for when there are no "Method X" headers (treat the whole body as one method)
        time_match = re.search(r'Time\s+Complexity:\s*([^\n\r]+)', body, re.IGNORECASE)
        space_match = re.search(r'Space\s+Complexity:\s*([^\n\r]+)', body, re.IGNORECASE)
        
        optimal_time = time_match.group(1).strip() if time_match else "O(N)"
        optimal_space = space_match.group(1).strip() if space_match else "O(N)"
        
        code = ""
        if space_match:
            start_pos = space_match.end()
            raw_code = body[start_pos:].strip()
            
            # Improved regex to handle leading indentation/spaces/tabs
            code_start_match = re.search(r'(?:^|\n)[ \t]*(?:def\s+|class\s+|import\s+|from\s+\S+\s+import|```[a-zA-Z]*)', raw_code)
            if code_start_match:
                raw_code = raw_code[code_start_match.start():].strip()
            
            # Clean up: remove "Code:" or "Reference Code:" if explicitly present
            raw_code = re.sub(r'^(Code|Reference Code):\s*', '', raw_code, flags=re.IGNORECASE)
            
            # Clean up: strip markdown backticks if present
            raw_code = re.sub(r'^```[a-zA-Z]*\s*', '', raw_code)
            raw_code = re.sub(r'\s*```$', '', raw_code)
            
            code = raw_code.strip()
            
        methods.append({
            "name": f"{problem_name} - Method 1 (Standard)",
            "pattern": "Standard",
            "difficulty": difficulty,
            "optimal_time": optimal_time,
            "optimal_space": optimal_space,
            "code": code,
            "description": description
        })
    else:
        for j, m_match in enumerate(method_matches):
            m_start = m_match.end()
            m_end = method_matches[j+1].start() if j + 1 < len(method_matches) else len(body)
            
            method_num = m_match.group(1).strip()
            method_name = m_match.group(2).strip() if m_match.group(2) else f"Method {method_num}"
            method_body = body[m_start:m_end]
            
            # Complexities
            time_match = re.search(r'Time\s+Complexity:\s*([^\n\r]+)', method_body, re.IGNORECASE)
            space_match = re.search(r'Space\s+Complexity:\s*([^\n\r]+)', method_body, re.IGNORECASE)
            
            optimal_time = time_match.group(1).strip() if time_match else "O(N)"
            optimal_space = space_match.group(1).strip() if space_match else "O(N)"
            
            # Extract code block: grab everything following the "Space Complexity" line
            code = ""
            if space_match:
                start_pos = space_match.end()
                raw_code = method_body[start_pos:].strip()
                
                # Improved regex to handle leading indentation/spaces/tabs
                code_start_match = re.search(r'(?:^|\n)[ \t]*(?:def\s+|class\s+|import\s+|from\s+\S+\s+import|```[a-zA-Z]*)', raw_code)
                if code_start_match:
                    raw_code = raw_code[code_start_match.start():].strip()
                
                # Clean up: remove "Code:" or "Reference Code:" if explicitly present
                raw_code = re.sub(r'^(Code|Reference Code):\s*', '', raw_code, flags=re.IGNORECASE)
                
                # Clean up: strip markdown backticks if present
                raw_code = re.sub(r'^```[a-zA-Z]*\s*', '', raw_code)
                raw_code = re.sub(r'\s*```$', '', raw_code)
                
                code = raw_code.strip()
                    
            methods.append({
                "name": f"{problem_name} - Method {method_num} ({method_name})",
                "pattern": method_name,
                "difficulty": difficulty,
                "optimal_time": optimal_time,
                "optimal_space": optimal_space,
                "code": code,
                "description": description
            })
            
    return methods

def parse_multi_problem_doc(text):
    # Find all problem headers: e.g. "1. Two Sum"
    matches = list(re.finditer(r'^\s*(\d+)\.\s*([^\n\r]+)', text, re.MULTILINE))
    
    problems = []
    for i, match in enumerate(matches):
        start_idx = match.end()
        end_idx = matches[i+1].start() if i + 1 < len(matches) else len(text)
        
        problem_number = int(match.group(1).strip())
        problem_name = match.group(2).strip()
        problem_body = text[start_idx:end_idx]
        
        parsed_methods = parse_problem_body(problem_name, problem_body)
        for m in parsed_methods:
            m['problem_number'] = problem_number
        problems.extend(parsed_methods)
        
    return problems

def sync_gdrive(client=None):
    if client is None:
        client = db.get_supabase_client()
        
    try:
        creds = get_credentials()
    except KeyError:
        return "GCP credentials not found in secrets.toml"
        
    drive_service = build('drive', 'v3', credentials=creds)
    docs_service = build('docs', 'v1', credentials=creds)
    
    folder_id = get_secret("GDRIVE_FOLDER_ID")
    if not folder_id:
        return "GDRIVE_FOLDER_ID not found in secrets.toml"
    
    query = f"'{folder_id}' in parents and mimeType='application/vnd.google-apps.document' and trashed=false"
    results = drive_service.files().list(q=query, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])
    
    inserted_count = 0
    updated_count = 0
    
    for item in items:
        doc_id = item['id']
        doc_name = item['name']
        db.log_trace(f"Sync: Processing Doc '{doc_name}' ({doc_id})")
        
        # Fetch doc content
        doc = docs_service.documents().get(documentId=doc_id).execute()
        doc_content = doc.get('body').get('content')
        full_text = extract_text_from_elements(doc_content)
        
        parsed_problems = parse_multi_problem_doc(full_text)
        db.log_trace(f"Sync: Parsed {len(parsed_problems)} methods from '{doc_name}'")
        
        for p in parsed_problems:
            # Check if this specific problem/method name exists in DB for this user
            existing = db.get_problem_by_name(p['name'], client)
            
            problem_data = {
                "name": p['name'],
                "problem_number": p.get('problem_number'),
                "pattern": p['pattern'],
                "difficulty": p['difficulty'],
                "google_doc_url": f"https://docs.google.com/document/d/{doc_id}/edit",
                "google_doc_id": doc_id,
                "optimal_time": p['optimal_time'],
                "optimal_space": p['optimal_space'],
                "reference_code": p['code'],
                "description": p.get('description', '')
            }
            
            db.log_trace(f"Sync: Method '{p['name']}' -> code length={len(p['code'])}")
            
            if not existing:
                # Insert problem
                db.log_trace(f"Sync: Inserting new problem: '{p['name']}'")
                prob_res = db.insert_problem(problem_data, client)
                db.log_trace(f"Sync: Insert result data: {prob_res.data if prob_res else 'None'}")
                
                # Insert review queue starting at Box 1
                if prob_res and prob_res.data:
                    prob_id = prob_res.data[0]['id']
                    db.insert_review({
                        "problem_id": prob_id,
                        "box_level": 1
                    }, client)
                    inserted_count += 1
            else:
                # Update problem in case anything changed
                db.log_trace(f"Sync: Updating existing problem: '{p['name']}' (ID={existing['id']})")
                update_res = db.update_problem(existing['id'], {
                    "problem_number": p.get('problem_number'),
                    "pattern": p['pattern'],
                    "difficulty": p['difficulty'],
                    "optimal_time": p['optimal_time'],
                    "optimal_space": p['optimal_space'],
                    "reference_code": p['code'],
                    "description": p.get('description', '')
                }, client)
                db.log_trace(f"Sync: Update result data: {update_res.data if update_res else 'None'}")
                updated_count += 1
                
            if p.get('problem_number'):
                db.insert_journey_progress(p['problem_number'], client)
                
    return f"Sync complete. Created {inserted_count} new methods, updated {updated_count} existing methods."