import sys, re

with open('/home/fc-abhay/PF/project-management-app/project-management-app-backend/backgroundtask/report_generate.py', 'r') as f:
    content = f.read()

# 1. Update filename and title in create_new_report
filename_old = 'filename = f"report_{job_id}.pdf"'
filename_new = '''
        safe_name = re.sub(r'[^a-zA-Z0-9_-]', '_', report_name or project_name)
        filename = f"{safe_name}_{str(job_id)[:8]}.pdf"
        pdf.set_title(report_name or project_name)
'''
content = content.replace(filename_old, filename_new)


# 2. Rewrite the loop block inside generate_project_report_pdf
start_marker = "    # ===============================\n    # PAGE X: DETAILED TICKET LOGS\n    # ==============================="
end_marker = "    # ===============================\n    # PAGE X: BACK PAGE\n    # ==============================="

start_idx = content.find(start_marker)
end_idx = content.find(end_marker)

if start_idx == -1 or end_idx == -1:
    print("Could not find markers")
    sys.exit(1)

new_code = """    # ===============================
    # PAGE X: DETAILED TICKET LOGS
    # ===============================
    
    first_ticket = True
    for t in report_json['tickets']:
        if not first_ticket:
            pdf.add_page()
        else:
            pdf.add_page()
            first_ticket = False
            
        # Background
        pdf.set_fill_color(248, 250, 252) # F8FAFC Background
        pdf.rect(0, 0, 210, 297, 'F')
        
        pdf.set_y(15)
        
        # 2. Hero Ticket Card
        hero_y = pdf.get_y()
        pdf.set_fill_color(255, 255, 255)
        pdf.set_draw_color(226, 232, 240)
        pdf.rect(15, hero_y, 180, 26, style='DF', round_corners=True, corner_radius=3)
        
        pdf.set_xy(20, hero_y + 4)
        pdf.set_font('helvetica', 'B', 8)
        pdf.set_text_color(99, 102, 241)
        t_id_str = safe_str(t.get('id', ''))
        pdf.cell(50, 4, f"{t_id_str}")
        
        t_priority = t.get('priority')
        if t_priority:
            pw = pdf.get_string_width(t_priority) + 8
            draw_pill(pdf, 195 - pw - 5, hero_y + 4, pw, 4, t_priority, (254,242,242), (220,38,38))
            
        pdf.set_xy(20, hero_y + 9)
        pdf.set_font('helvetica', 'B', 13) 
        pdf.set_text_color(15, 23, 42)
        title = t.get('title', '')
        if len(title) > 65: title = title[:62] + "..."
        pdf.cell(100, 6, safe_str(title))
        
        px = 20
        py = hero_y + 18
        t_type = t.get('type')
        if t_type:
            tw = pdf.get_string_width(t_type) + 6
            draw_pill(pdf, px, py, tw, 4, t_type, (224,242,254), (2,132,199))
            px += tw + 4
            
        t_status = t.get('status')
        if t_status:
            sw = pdf.get_string_width(t_status) + 6
            draw_pill(pdf, px, py, sw, 4, t_status, (220,252,231), (22,163,74))
            px += sw + 4
            
        t_sp = str(t.get('story_points') or "-")
        spw = pdf.get_string_width(f"SP: {t_sp}") + 6
        draw_pill(pdf, px, py, spw, 4, f"SP: {t_sp}", (243,232,255), (147,51,234))
        
        pdf.set_y(hero_y + 30)
        
        col_split_y = pdf.get_y()
        
        # Metadata Row 
        pdf.set_fill_color(255, 255, 255)
        pdf.set_draw_color(226, 232, 240)
        pdf.rect(15, col_split_y, 115, 14, style='DF', round_corners=True, corner_radius=2)
        
        pdf.set_font('helvetica', 'B', 6)
        pdf.set_text_color(148, 163, 184)
        pdf.set_xy(24, col_split_y + 2)
        pdf.cell(36, 4, "REPORTER")
        pdf.set_xy(64, col_split_y + 2)
        pdf.cell(36, 4, "ASSIGNEES")
        
        # Simple Person Icon for Reporter
        pdf.set_draw_color(148, 163, 184)
        pdf.set_line_width(0.3)
        pdf.ellipse(20, col_split_y + 3, 2, 2, 'D')
        pdf.arc(19, col_split_y + 5, 4, 3, 180, 360, style='D')
        
        # Simple Persons Icon for Assignees
        pdf.ellipse(60, col_split_y + 3, 2, 2, 'D')
        pdf.arc(59, col_split_y + 5, 4, 3, 180, 360, style='D')
        
        pdf.set_font('helvetica', '', 7)
        pdf.set_text_color(15, 23, 42)
        pdf.set_xy(20, col_split_y + 6)
        rep = safe_str(t.get('reporter', 'Unknown'))
        if len(rep)>18: rep = rep[:15]+"..."
        pdf.cell(40, 4, rep)
        
        ass = ", ".join(t.get('assignees', []))
        if not ass: ass = "Unassigned"
        if len(ass)>30: ass = ass[:27]+"..."
        pdf.set_xy(60, col_split_y + 6)
        pdf.cell(40, 4, safe_str(ass))
        
        # Right Column (Ticket Summary Box)
        rx = 135
        pdf.set_fill_color(248, 250, 252) # Slate-50
        pdf.set_draw_color(226, 232, 240) # Slate-200
        pdf.set_line_width(0.2)
        pdf.rect(rx, col_split_y, 60, 35, style='DF', round_corners=True, corner_radius=3)
        
        pdf.set_font('helvetica', 'B', 7)
        pdf.set_text_color(100, 116, 139) # Slate-500
        pdf.set_xy(rx + 5, col_split_y + 4)
        pdf.cell(50, 4, "TICKET SUMMARY")
        pdf.set_draw_color(226, 232, 240)
        pdf.line(rx + 5, col_split_y + 9, rx + 55, col_split_y + 9)
        
        pdf.set_font('helvetica', '', 7)
        pdf.set_text_color(71, 85, 105)
        pdf.set_xy(rx + 5, col_split_y + 11)
        pdf.cell(20, 5, "Status")
        if t_status: draw_pill(pdf, rx + 40, col_split_y + 11.5, 15, 4, t_status, (220,252,231), (22,163,74))
        
        pdf.set_xy(rx + 5, col_split_y + 18)
        pdf.cell(20, 5, "Priority")
        if t_priority: draw_pill(pdf, rx + 40, col_split_y + 18.5, 15, 4, t_priority, (254,242,242), (220,38,38))
        
        pdf.set_xy(rx + 5, col_split_y + 25)
        pdf.cell(20, 5, "Type")
        if t_type: draw_pill(pdf, rx + 40, col_split_y + 25.5, 15, 4, t_type, (224,242,254), (2,132,199))
        
        # Right Column (Timeline Header)
        pdf.set_xy(rx, col_split_y + 40)
        pdf.set_font('helvetica', 'B', 7)
        pdf.set_text_color(100, 116, 139)
        pdf.cell(60, 5, "TIMELINE")
        
        timeline_events = []
        for c in t.get('comments', []):
            timeline_events.append({'dt': c['dt'], 'type': 'comment', 'data': c})
        for a in t.get('activity_logs', []):
            timeline_events.append({'dt': a['dt'], 'type': 'activity', 'data': a})
            
        timeline_events.sort(key=lambda x: x['dt'], reverse=True)
        
        ty = col_split_y + 46
        for evt in timeline_events[:6]:
            if ty > 260: break
            
            # Avatar placeholder
            pdf.set_fill_color(226, 232, 240) # slate-200
            pdf.ellipse(rx + 1, ty, 4, 4, 'F')
            
            actor = ""
            if evt['type'] == 'comment': actor = safe_str(evt['data']['author'])
            else: actor = safe_str(evt['data']['actor'])
            if actor:
                pdf.set_xy(rx + 1, ty + 0.5)
                pdf.set_font('helvetica', 'B', 5)
                pdf.set_text_color(71, 85, 105)
                pdf.cell(4, 3, actor[0].upper(), align='C')
            
            pdf.set_draw_color(226, 232, 240)
            pdf.line(rx + 3, ty + 5, rx + 3, ty + 10) # subtle thin line
            
            pdf.set_xy(rx + 7, ty - 1)
            pdf.set_font('helvetica', '', 6)
            pdf.set_text_color(148, 163, 184)
            pdf.cell(50, 3, safe_str(get_time_ago(evt['dt'])))
            
            pdf.set_xy(rx + 7, ty + 2)
            pdf.set_font('helvetica', 'B', 7)
            pdf.set_text_color(15, 23, 42)
            pdf.cell(50, 4, actor)
            
            action_text = ""
            if evt['type'] == 'comment':
                action_text = "Commented on ticket"
            else:
                action_text = safe_str(evt['data']['action'])
                if evt['data'].get('new_value'):
                    action_text += f" to {evt['data']['new_value']}"
            
            pdf.set_xy(rx + 7, ty + 6)
            pdf.set_font('helvetica', '', 6)
            pdf.set_text_color(100, 116, 139)
            if len(action_text) > 35: action_text = action_text[:32] + "..."
            pdf.cell(50, 3, action_text)
                
            ty += 11
        
        # Left column downwards
        pdf.set_y(col_split_y + 18)
        
        pdf.set_font('helvetica', 'B', 7)
        pdf.set_text_color(100, 116, 139)
        pdf.cell(115, 5, "DESCRIPTION", new_x=XPos.LMARGIN, new_y=YPos.NEXT)
        
        desc = t.get('description')
        if desc:
            desc_y_start = pdf.get_y()
            pdf.set_y(desc_y_start + 1)
            
            pdf.set_font('helvetica', '', 7)
            pdf.set_text_color(51, 65, 85)
            
            # Simple markdown to HTML parser for FPDF write_html
            def md_to_html(md_text):
                # Bold
                md_text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', md_text)
                # Italic
                md_text = re.sub(r'\*(.+?)\*', r'<i>\1</i>', md_text)
                # Strikethrough
                md_text = re.sub(r'~~(.+?)~~', r'<del>\1</del>', md_text)
                # Lists
                md_text = re.sub(r'(?m)^- (.*)$', r'<li>\1</li>', md_text)
                # Wrap lists in ul (very naive, but FPDF handles random li's okay)
                return md_text

            parts = re.split(r'(!\[.*?\]\((.*?)\))', safe_str(desc))
            idx = 0
            while idx < len(parts):
                if parts[idx].startswith('!['):
                    url = parts[idx+1]
                    try:
                        tmp_path = None
                        is_tmp = False
                        if "uploads/" in url:
                            filename = url.split("uploads/")[-1]
                            local_path = os.path.join(os.getcwd(), "uploads", filename)
                            if os.path.exists(local_path):
                                tmp_path = local_path
                                
                        if not tmp_path:
                            req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
                            with urllib.request.urlopen(req) as response:
                                with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
                                    tmp.write(response.read())
                                    tmp_path = tmp.name
                                    is_tmp = True
                        
                        img_info = pdf.image(tmp_path, x=15, w=115)
                        if img_info:
                            pdf.set_y(pdf.get_y() + img_info.rendered_height + 2)
                        if is_tmp:
                            os.remove(tmp_path)
                    except Exception as e:
                        pdf.set_y(pdf.get_y() + 2)
                        err_y = pdf.get_y()
                        pdf.set_draw_color(254, 202, 202) # red-200
                        pdf.set_fill_color(255, 255, 255)
                        pdf.rect(15, err_y, 115, 8, 'DF', round_corners=True, corner_radius=1.5)
                        pdf.set_text_color(220, 38, 38)
                        pdf.set_xy(18, err_y + 2)
                        pdf.set_font('helvetica', '', 6)
                        pdf.cell(100, 4, "[Image failed to load]")
                        pdf.set_y(err_y + 10)
                        pdf.set_draw_color(226, 232, 240)
                    idx += 3
                else:
                    text_chunk = parts[idx].strip()
                    if text_chunk:
                        pdf.set_x(15)
                        # Use write_html for cleaner formatting
                        html_content = md_to_html(text_chunk)
                        
                        # Set right margin to constrain width to 115mm (210 - 15 - 115 = 80)
                        pdf.set_right_margin(80)
                        pdf.set_font('helvetica', '', 7)
                        pdf.set_text_color(51, 65, 85)
                        
                        # wrap text in <p> to ensure proper parsing
                        html_content = html_content.replace('\n', '<br>')
                        
                        try:
                            pdf.write_html(f'<font color="#334155" face="helvetica" size="7">{html_content}</font>')
                        except:
                            # Fallback if html parser fails
                            pdf.multi_cell(115, 4, text_chunk, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
                            
                        pdf.set_right_margin(15) # reset margin
                        pdf.ln(2)
                    idx += 1
            pdf.ln(4)
        
        # Comments Section
        comments = t.get('comments', [])
        if comments:
            pdf.ln(2)
            pdf.set_font('helvetica', 'B', 7)
            pdf.set_text_color(100, 116, 139)
            pdf.cell(115, 6, "COMMENTS", new_x=XPos.LMARGIN, new_y=YPos.NEXT)
            
            for c in comments:
                if pdf.get_y() > 260: pdf.add_page()
                cy = pdf.get_y()
                
                # Avatar
                pdf.set_fill_color(226, 232, 240)
                pdf.ellipse(15, cy + 1, 4, 4, 'F')
                pdf.set_xy(15, cy + 1.5)
                pdf.set_font('helvetica', 'B', 5)
                pdf.set_text_color(71, 85, 105)
                author = safe_str(c['author'])
                pdf.cell(4, 3, author[0].upper() if author else "?", align='C')
                
                # Connector line
                pdf.set_draw_color(226, 232, 240)
                pdf.line(17, cy + 6, 17, cy + 14) 
                
                pdf.set_xy(21, cy)
                pdf.set_font('helvetica', 'B', 7)
                pdf.set_text_color(15, 23, 42)
                pdf.cell(pdf.get_string_width(author) + 2, 4, author)
                pdf.set_font('helvetica', '', 6)
                pdf.set_text_color(148, 163, 184)
                pdf.cell(20, 4, safe_str(get_time_ago(c['dt'])))
                
                pdf.set_y(cy + 4.5)
                pdf.set_x(21)
                
                # Minimal Comment Box
                cbox_y = pdf.get_y()
                pdf.set_fill_color(255, 255, 255) 
                pdf.set_draw_color(226, 232, 240)
                pdf.rect(21, cbox_y, 109, 10, 'DF', round_corners=True, corner_radius=2)
                
                pdf.set_y(cbox_y + 2)
                pdf.set_x(24)
                pdf.set_font('helvetica', '', 7)
                pdf.set_text_color(51, 65, 85)
                pdf.multi_cell(103, 4, safe_str(c['text']), new_x=XPos.LMARGIN, new_y=YPos.NEXT)
                
                cbox_end_y = pdf.get_y() + 2
                pdf.set_fill_color(255, 255, 255)
                pdf.rect(21, cbox_y, 109, cbox_end_y - cbox_y, 'DF', round_corners=True, corner_radius=2)
                
                # Redraw text
                pdf.set_y(cbox_y + 2)
                pdf.set_x(24)
                pdf.set_font('helvetica', '', 7)
                pdf.set_text_color(51, 65, 85)
                pdf.multi_cell(103, 4, safe_str(c['text']), new_x=XPos.LMARGIN, new_y=YPos.NEXT)
                
                pdf.set_y(cbox_end_y + 4)
                
        # Activity Log Section
        activities = t.get('activity_logs', [])
        if activities:
            pdf.ln(2)
            pdf.set_font('helvetica', 'B', 7)
            pdf.set_text_color(100, 116, 139)
            pdf.cell(115, 6, "ACTIVITY LOG", new_x=XPos.LMARGIN, new_y=YPos.NEXT)
            
            for a in activities:
                if pdf.get_y() > 260: pdf.add_page()
                ay = pdf.get_y()
                
                # Subtle small dot
                pdf.set_fill_color(203, 213, 225)
                pdf.ellipse(16.5, ay + 1.5, 1.5, 1.5, 'F')
                pdf.set_draw_color(226, 232, 240)
                pdf.line(17.25, ay + 4, 17.25, ay + 8)
                
                pdf.set_xy(21, ay)
                pdf.set_font('helvetica', '', 7)
                pdf.set_text_color(51, 65, 85)
                
                actor = safe_str(a['actor'])
                action_text = safe_str(a['action'])
                old_v = safe_str(a.get('old_value', ''))
                new_v = safe_str(a.get('new_value', ''))
                if old_v and new_v: action_text += f" from {old_v} to {new_v}"
                elif new_v: action_text += f" to {new_v}"
                elif old_v: action_text += f" removed {old_v}"
                
                pdf.cell(115, 4, f"{actor} {action_text}", new_x=XPos.LMARGIN, new_y=YPos.NEXT)
                
                pdf.set_x(21)
                pdf.set_font('helvetica', '', 6)
                pdf.set_text_color(148, 163, 184)
                pdf.cell(0, 3, safe_str(get_time_ago(a['dt'])), new_x=XPos.LMARGIN, new_y=YPos.NEXT)
                pdf.ln(2)

"""

new_content = content[:start_idx] + new_code + "\n" + content[end_idx:]

with open('/home/fc-abhay/PF/project-management-app/project-management-app-backend/backgroundtask/report_generate.py', 'w') as f:
    f.write(new_content)

print("Patched successfully")
