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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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
"""
Google Docs Writer Module
Formats and appends/updates LeetCode problems directly in Google Docs with rich styling:
- Headings (HEADING_3 for Title, HEADING_5 for Difficulty, HEADING_4 for Pattern / How to solve)
- Difficulty badge colors (Easy: Green, Medium: Orange, Hard: Red)
- Grey inline pills for Example inputs/outputs & Constraints
- Bulleted Constraints lists
- Syntax-highlighted code blocks (Courier New 11.5pt, Blue keywords, Green comments)
"""

import re

from googleapiclient.discovery import build

import gdrive_sync

# Google Docs Color Constants
COLOR_EASY = {"red": 0.0745, "green": 0.4862, "blue": 0.2117}  # #137c36
COLOR_MEDIUM = {"red": 0.750, "green": 0.380, "blue": 0.0}  # #c06100
COLOR_HARD = {"red": 0.7725, "green": 0.1333, "blue": 0.1215}  # #c5221f
COLOR_GREY_BG = {"red": 0.8509, "green": 0.8509, "blue": 0.8509}  # #d9d9d9
COLOR_CODE_KW = {"red": 0.0, "green": 0.0, "blue": 1.0}  # #0000ff
COLOR_CODE_COMMENT = {"red": 0.0745, "green": 0.4862, "blue": 0.2117}  # #137c36
COLOR_VAR_GREEN = {"red": 0.0941, "green": 0.5019, "blue": 0.2196}

PYTHON_KEYWORDS = {
    "False",
    "None",
    "True",
    "and",
    "as",
    "assert",
    "async",
    "await",
    "break",
    "class",
    "continue",
    "def",
    "del",
    "elif",
    "else",
    "except",
    "finally",
    "for",
    "from",
    "global",
    "if",
    "import",
    "in",
    "is",
    "lambda",
    "nonlocal",
    "not",
    "or",
    "pass",
    "raise",
    "return",
    "try",
    "while",
    "with",
    "yield",
    "match",
    "case",
    "type",
    "self",
    "int",
    "str",
    "bool",
    "float",
    "list",
    "dict",
    "set",
    "tuple",
    "List",
    "Dict",
    "Set",
    "Tuple",
    "Optional",
}


def get_docs_service():
    creds = gdrive_sync.get_credentials()
    return build("docs", "v1", credentials=creds)


def get_target_doc_id():
    # Return default or configured document ID
    doc_id = gdrive_sync.get_secret("GDRIVE_DEFAULT_DOC_ID")
    if not doc_id:
        # Fallback to the known main document if present in secrets
        doc_id = (
            gdrive_sync.get_secret("DEFAULT_GOOGLE_DOC_ID")
            or "1E3YVG53LxGOaOGc8-wHIPye4-fPLTOobwfSUvgZax80"
        )
    return doc_id


class DocBuilder:
    """Helper to build text and track character ranges for styling."""

    def __init__(self, base_index: int = 1):
        self.base_index = base_index
        self.text_parts = []
        self.current_len = 0
        self.paragraph_styles = []  # (start, end, namedStyleType)
        self.text_styles = []  # (start, end, style_dict, fields_str)
        self.bullets = []  # (start, end)

    def add_text(
        self,
        text: str,
        bold=False,
        italic=False,
        fg_color=None,
        bg_color=None,
        font_family=None,
        font_size_pt=None,
    ):
        start = self.current_len
        self.text_parts.append(text)
        self.current_len += len(text)
        end = self.current_len

        style = {}
        fields = []
        if bold:
            style["bold"] = True
            fields.append("bold")
        if italic:
            style["italic"] = True
            fields.append("italic")
        if fg_color:
            style["foregroundColor"] = {"color": {"rgbColor": fg_color}}
            fields.append("foregroundColor")
        if bg_color:
            style["backgroundColor"] = {"color": {"rgbColor": bg_color}}
            fields.append("backgroundColor")
        if font_family:
            style["weightedFontFamily"] = {"fontFamily": font_family}
            fields.append("weightedFontFamily")
        if font_size_pt:
            style["fontSize"] = {"magnitude": font_size_pt, "unit": "PT"}
            fields.append("fontSize")

        if fields:
            self.text_styles.append((start, end, style, ",".join(fields)))
        return start, end

    def add_paragraph(self, text: str, style_type="NORMAL_TEXT", is_bullet=False, **text_kwargs):
        if not text.endswith("\n"):
            text += "\n"
        start = self.current_len
        self.add_text(text, **text_kwargs)
        end = self.current_len
        self.paragraph_styles.append((start, end, style_type))
        if is_bullet:
            self.bullets.append((start, end))
        return start, end

    def get_full_text(self) -> str:
        return "".join(self.text_parts)

    def generate_requests(self) -> list:
        requests = []
        full_text = self.get_full_text()
        if not full_text:
            return requests

        # 1. Insert text request
        requests.append({"insertText": {"location": {"index": self.base_index}, "text": full_text}})

        # 2. Paragraph style requests
        for start, end, style_type in self.paragraph_styles:
            requests.append(
                {
                    "updateParagraphStyle": {
                        "range": {
                            "startIndex": self.base_index + start,
                            "endIndex": self.base_index + end,
                        },
                        "paragraphStyle": {"namedStyleType": style_type},
                        "fields": "namedStyleType",
                    }
                }
            )

        # 3. Bullets
        for start, end in self.bullets:
            requests.append(
                {
                    "createParagraphBullets": {
                        "range": {
                            "startIndex": self.base_index + start,
                            "endIndex": self.base_index + end,
                        },
                        "bulletPreset": "BULLET_DISC_CIRCLE_SQUARE",
                    }
                }
            )

        # 4. Text style requests
        for start, end, style, fields in self.text_styles:
            requests.append(
                {
                    "updateTextStyle": {
                        "range": {
                            "startIndex": self.base_index + start,
                            "endIndex": self.base_index + end,
                        },
                        "textStyle": style,
                        "fields": fields,
                    }
                }
            )

        return requests


def format_code_lines(builder: DocBuilder, code: str):
    """Formats python code with monospace font, blue keywords, and green comments with emojis."""
    lines = code.split("\n")
    for line in lines:
        if not line:
            builder.add_paragraph(
                "", style_type="NORMAL_TEXT", font_family="Courier New", font_size_pt=11.5
            )
            continue

        # Check for full line comment
        stripped = line.strip()
        if stripped.startswith("#"):
            builder.add_paragraph(
                line,
                style_type="NORMAL_TEXT",
                fg_color=COLOR_CODE_COMMENT,
                font_family="Courier New",
                font_size_pt=11.5,
            )
            continue

        # Check for inline comment
        comment_idx = line.find("#")
        code_part = line if comment_idx == -1 else line[:comment_idx]
        comment_part = "" if comment_idx == -1 else line[comment_idx:]

        # Tokenize code part for keywords and tokens
        tokens = re.split(r"(\b[a-zA-Z_][a-zA-Z0-9_]*\b|[0-9]+|\s+|[^\w\s])", code_part)
        for token in tokens:
            if not token:
                continue
            if token in PYTHON_KEYWORDS:
                builder.add_text(
                    token, fg_color=COLOR_CODE_KW, font_family="Courier New", font_size_pt=11.5
                )
            elif token.isdigit():
                builder.add_text(
                    token, fg_color=COLOR_CODE_COMMENT, font_family="Courier New", font_size_pt=11.5
                )
            else:
                builder.add_text(token, font_family="Courier New", font_size_pt=11.5)

        if comment_part:
            builder.add_text(
                comment_part,
                fg_color=COLOR_CODE_COMMENT,
                font_family="Courier New",
                font_size_pt=11.5,
            )

        # End line
        builder.add_paragraph("", style_type="NORMAL_TEXT")


def build_full_problem_doc_content(
    base_index: int,
    problem_number: int | None,
    problem_name: str,
    difficulty: str,
    pattern: str,
    description: str,
    examples: list | str,
    constraints: list | str,
    optimal_time: str,
    optimal_space: str,
    how_to_solve: str,
    reference_code: str,
    method_name: str = "Standard",
) -> DocBuilder:
    """Builds complete new problem document content."""
    builder = DocBuilder(base_index)

    # Spacing before problem
    builder.add_paragraph("", style_type="NORMAL_TEXT")
    builder.add_paragraph("", style_type="NORMAL_TEXT")

    # 1. Problem Header: e.g. "2. Add Two Numbers" or "Two Sum"
    title_str = f"{problem_number}. {problem_name}" if problem_number else problem_name
    builder.add_paragraph(title_str, style_type="HEADING_3")

    # 2. Difficulty Badge
    diff_norm = (difficulty or "Medium").capitalize()
    diff_color = (
        COLOR_EASY if diff_norm == "Easy" else (COLOR_HARD if diff_norm == "Hard" else COLOR_MEDIUM)
    )
    builder.add_paragraph(diff_norm, style_type="HEADING_5", fg_color=diff_color)

    # 3. Description
    if description and description.strip():
        for para in description.strip().split("\n\n"):
            if para.strip():
                builder.add_paragraph(para.strip(), style_type="NORMAL_TEXT")
        builder.add_paragraph("", style_type="NORMAL_TEXT")

    # 4. Examples
    if examples:
        if isinstance(examples, str):
            # Parse string examples if needed or print directly
            builder.add_paragraph(examples.strip(), style_type="NORMAL_TEXT")
        elif isinstance(examples, list):
            for i, ex in enumerate(examples, start=1):
                builder.add_paragraph(f"Example {i}:", style_type="NORMAL_TEXT", bold=True)
                if isinstance(ex, dict):
                    inp = ex.get("input", "")
                    out = ex.get("output", "")
                    exp = ex.get("explanation", "")
                    if inp:
                        builder.add_text("Input: ")
                        builder.add_text(f" {inp} \n", bg_color=COLOR_GREY_BG)
                    if out:
                        builder.add_text("Output: ")
                        builder.add_text(f" {out} \n", bg_color=COLOR_GREY_BG)
                    if exp:
                        builder.add_text("Explanation: ")
                        builder.add_text(f" {exp} \n", bg_color=COLOR_GREY_BG)
                else:
                    builder.add_paragraph(str(ex), style_type="NORMAL_TEXT")
                builder.add_paragraph("", style_type="NORMAL_TEXT")

    # 5. Constraints
    if constraints:
        builder.add_paragraph("Constraints:", style_type="NORMAL_TEXT", bold=True)
        if isinstance(constraints, str):
            c_list = [c.strip() for c in constraints.split("\n") if c.strip()]
        else:
            c_list = constraints

        for c in c_list:
            clean_c = re.sub(r"^[•\-\*]\s*", "", c).strip()
            if clean_c:
                builder.add_paragraph(
                    clean_c, style_type="NORMAL_TEXT", is_bullet=True, bg_color=COLOR_GREY_BG
                )
        builder.add_paragraph("", style_type="NORMAL_TEXT")

    # 6. Method / Pattern
    builder.add_paragraph("Method:", style_type="NORMAL_TEXT", bold=True)
    builder.add_paragraph("Pattern:", style_type="NORMAL_TEXT")
    pat_str = pattern.strip() if pattern and pattern.strip() else "Standard"
    builder.add_paragraph(f"{pat_str} ", style_type="HEADING_4")

    # 7. Complexities
    time_str = optimal_time.strip() if optimal_time else "O(N)"
    space_str = optimal_space.strip() if optimal_space else "O(N)"

    builder.add_text("Time Complexity:", bold=True)
    builder.add_paragraph(f"  {time_str}", style_type="NORMAL_TEXT")

    builder.add_text("Space Complexity:", bold=True)
    builder.add_paragraph(f"  {space_str}\n", style_type="NORMAL_TEXT")

    # 8. How to solve? (Intuition)
    if how_to_solve and how_to_solve.strip():
        builder.add_paragraph("How to solve?", style_type="HEADING_4")
        for para in how_to_solve.strip().split("\n\n"):
            if para.strip():
                builder.add_paragraph(para.strip(), style_type="NORMAL_TEXT")
        builder.add_paragraph("", style_type="NORMAL_TEXT")

    # 9. Reference Code
    if reference_code and reference_code.strip():
        format_code_lines(builder, reference_code.strip())

    return builder


def build_additional_method_content(
    base_index: int,
    method_num: int,
    pattern: str,
    optimal_time: str,
    optimal_space: str,
    how_to_solve: str,
    reference_code: str,
) -> DocBuilder:
    """Builds an additional method section to append under an existing problem."""
    builder = DocBuilder(base_index)

    builder.add_paragraph("", style_type="NORMAL_TEXT")
    builder.add_paragraph(f"Method {method_num}:", style_type="NORMAL_TEXT", bold=True)
    builder.add_paragraph("Pattern:", style_type="NORMAL_TEXT")
    pat_str = pattern.strip() if pattern and pattern.strip() else f"Method {method_num}"
    builder.add_paragraph(f"{pat_str} ", style_type="HEADING_4")

    time_str = optimal_time.strip() if optimal_time else "O(N)"
    space_str = optimal_space.strip() if optimal_space else "O(N)"

    builder.add_text("Time Complexity:", bold=True)
    builder.add_paragraph(f"  {time_str}", style_type="NORMAL_TEXT")

    builder.add_text("Space Complexity:", bold=True)
    builder.add_paragraph(f"  {space_str}\n", style_type="NORMAL_TEXT")

    if how_to_solve and how_to_solve.strip():
        builder.add_paragraph("How to solve?", style_type="HEADING_4")
        for para in how_to_solve.strip().split("\n\n"):
            if para.strip():
                builder.add_paragraph(para.strip(), style_type="NORMAL_TEXT")
        builder.add_paragraph("", style_type="NORMAL_TEXT")

    if reference_code and reference_code.strip():
        format_code_lines(builder, reference_code.strip())

    return builder


def find_problem_in_doc_content(content: list, problem_number: int | None, problem_name: str):
    """
    Scans the Google Doc structural content to check if problem exists.
    Returns: (found: bool, problem_start_idx, problem_end_idx, next_method_num)
    """
    clean_name = problem_name.lower().strip()

    # Track all problem headers and their locations
    problem_sections = []

    for elem in content:
        if "paragraph" in elem:
            p = elem["paragraph"]
            p_style = p.get("paragraphStyle", {}).get("namedStyleType", "")
            txt = "".join(
                tr.get("textRun", {}).get("content", "")
                for tr in p.get("elements", [])
                if "textRun" in tr
            ).strip()

            # Check if this paragraph is a problem title (HEADING_3 or starts with problem number)
            is_prob_header = False
            p_num = None
            p_title = ""

            num_match = re.match(r"^(\d+)\.\s*(.*)", txt)
            if num_match:
                is_prob_header = True
                p_num = int(num_match.group(1))
                p_title = num_match.group(2).strip().lower()
            elif p_style == "HEADING_3" and txt:
                is_prob_header = True
                p_title = txt.lower()

            if is_prob_header:
                start_i = elem.get("startIndex", 1)
                end_i = elem.get("endIndex", start_i)
                problem_sections.append(
                    {
                        "num": p_num,
                        "title": p_title,
                        "start_index": start_i,
                        "end_index": end_i,
                        "methods_count": 1,
                    }
                )

    if not problem_sections:
        return False, None, None, 1

    # Find matching section
    matched_idx = -1
    for idx, sec in enumerate(problem_sections):
        if problem_number and sec["num"] == problem_number:
            matched_idx = idx
            break
        if clean_name in sec["title"] or sec["title"] in clean_name:
            matched_idx = idx
            break

    if matched_idx == -1:
        return False, None, None, 1

    # Found match!
    curr_sec = problem_sections[matched_idx]
    # End index of this problem is start of next problem or end of document
    if matched_idx + 1 < len(problem_sections):
        end_boundary = problem_sections[matched_idx + 1]["start_index"]
    else:
        # Last element in doc
        end_boundary = content[-1].get("endIndex", 1) - 1

    # Count methods inside this boundary
    method_count = 1
    for elem in content:
        start_i = elem.get("startIndex", 0)
        if curr_sec["start_index"] <= start_i < end_boundary:
            if "paragraph" in elem:
                txt = "".join(
                    tr.get("textRun", {}).get("content", "")
                    for tr in elem["paragraph"].get("elements", [])
                    if "textRun" in tr
                )
                if re.search(r"Method\s*\d*:", txt, re.IGNORECASE):
                    method_count += 1

    return True, curr_sec["start_index"], end_boundary, max(method_count, 2)


def append_or_update_problem_in_doc(
    doc_id: str | None,
    problem_number: int | None,
    problem_name: str,
    difficulty: str,
    pattern: str,
    description: str,
    examples: list | str,
    constraints: list | str,
    optimal_time: str,
    optimal_space: str,
    how_to_solve: str,
    reference_code: str,
    method_name: str = "",
) -> dict:
    """
    Main entrypoint: Appends a new styled problem or updates an existing problem with an additional method.
    """
    if not doc_id:
        doc_id = get_target_doc_id()

    docs_service = get_docs_service()
    doc = docs_service.documents().get(documentId=doc_id).execute()
    content = doc.get("body", {}).get("content", [])

    exists, prob_start, prob_end, next_method_num = find_problem_in_doc_content(
        content, problem_number, problem_name
    )

    if exists and prob_end:
        # Append as Method X under existing problem
        insert_index = max(1, prob_end - 1)
        builder = build_additional_method_content(
            base_index=insert_index,
            method_num=next_method_num,
            pattern=pattern or method_name,
            optimal_time=optimal_time,
            optimal_space=optimal_space,
            how_to_solve=how_to_solve,
            reference_code=reference_code,
        )
        action_msg = f"Appended Method {next_method_num} to existing problem in Google Doc"
    else:
        # Append as new problem at end of doc
        doc_end_index = content[-1].get("endIndex", 1) - 1 if content else 1
        insert_index = max(1, doc_end_index)
        builder = build_full_problem_doc_content(
            base_index=insert_index,
            problem_number=problem_number,
            problem_name=problem_name,
            difficulty=difficulty,
            pattern=pattern,
            description=description,
            examples=examples,
            constraints=constraints,
            optimal_time=optimal_time,
            optimal_space=optimal_space,
            how_to_solve=how_to_solve,
            reference_code=reference_code,
            method_name=method_name,
        )
        action_msg = f"Appended new problem '{problem_name}' to Google Doc"

    requests = builder.generate_requests()
    if requests:
        res = (
            docs_service.documents()
            .batchUpdate(documentId=doc_id, body={"requests": requests})
            .execute()
        )
        return {
            "success": True,
            "doc_id": doc_id,
            "doc_url": f"https://docs.google.com/document/d/{doc_id}/edit",
            "message": action_msg,
            "response": res,
        }

    return {"success": True, "message": "No changes generated"}