""" 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"}