struct MarkdownRenderer: View {
    let text: String
    let role: String
    let streaming: Bool
    let defaultFontSize: CGFloat

    @State private var parsedContent: [ParsedContent] = []
    @State private var lastParsedText: String = ""
    
    init(text: String, role: String, streaming: Bool, defaultFontSize: CGFloat? = nil) {
        self.text = text
        self.role = role
        self.streaming = streaming
        self.defaultFontSize = defaultFontSize ?? 16
    }

    enum ParsedContent: Identifiable {
        case text(NSAttributedString)
        case code(CodeBlock)
        
        var id: UUID {
            switch self {
            case .text:
                return UUID()
            case .code(let codeBlock):
                return codeBlock.id
            }
        }
    }
    
    struct CodeBlock: Identifiable {
        let id = UUID()
        let code: String
        let language: String?
    }
    
    
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 0) {
                ForEach(parsedContent, id: \.id) { content in
                    switch content {
                    case .text(let attributedString):
                        Text(AttributedString(attributedString))
                            .lineSpacing(4)
                            .textSelection(.enabled)
                        
                    case .code(let codeBlock):
                        CodeBlockView(code: codeBlock.code, language: codeBlock.language, defaultFontSize: defaultFontSize)
                    }
                }
            }
        }
        .scrollContentBackground(.hidden)
        .padding(4)
        .onAppear {
            parseMarkdown()
        }
        .onChange(of: text) {
            parseMarkdown()
        }
    }
    
    private func parseMarkdown() {
        let paragraphs = text.components(separatedBy: .newlines)
        var currentCodeBlock: String?
        var currentCodeLanguage: String?
        var parsedContent: [ParsedContent] = []
        var currentTextBlock = NSMutableAttributedString()
        
        let codeBlockRegex = try? NSRegularExpression(pattern: "^\\s*```\\s*(.*)$", options: [])

        func appendCurrentTextBlock() {
            if currentTextBlock.length > 0 {
                parsedContent.append(.text(currentTextBlock))
                currentTextBlock = NSMutableAttributedString()
            }
        }
        
        func isCodeBlockStart(_ line: String) -> Bool {
            if let backtickIndex = line.firstIndex(of: "`") {
                let prefix = line[..<backtickIndex]
                return prefix.allSatisfy({ $0.isWhitespace }) && line[backtickIndex...].hasPrefix("```")
            }
            return false
        }
        
        for (index, paragraph) in paragraphs.enumerated() {
            if isCodeBlockStart(paragraph) {
                if currentCodeBlock == nil {
                    appendCurrentTextBlock()
                    currentCodeBlock = ""
                    if let match = codeBlockRegex?.firstMatch(in: paragraph, options: [], range: NSRange(location: 0, length: paragraph.utf16.count)),
                       let languageRange = Range(match.range(at: 1), in: paragraph) {
                        currentCodeLanguage = String(paragraph[languageRange]).trimmingCharacters(in: .whitespaces)
                    }
                } else {
                    parsedContent.append(.code(CodeBlock(code: currentCodeBlock!, language: currentCodeLanguage)))
                    currentCodeBlock = nil
                    currentCodeLanguage = nil
                }
            } else if currentCodeBlock != nil {
                currentCodeBlock!.append(paragraph + "\n")
            } else {
                let paragraphStyle = NSMutableParagraphStyle()
                paragraphStyle.paragraphSpacing = 10
                
                let attributes: [NSAttributedString.Key: Any] = [
                    .font: NSFont.systemFont(ofSize: defaultFontSize),
                    .foregroundColor: role == "assistant" ? NSColor.textColor : NSColor.secondaryLabelColor,
                    .paragraphStyle: paragraphStyle
                ]
                
                let attributedParagraph = NSMutableAttributedString(string: paragraph, attributes: attributes)
                let attributedParagraphCopy = attributedParagraph
                
                do {
                    try applyMarkdownFormatting(to: attributedParagraph)
                    currentTextBlock.append(attributedParagraph)
                } catch {
                    print("Error applying Markdown formatting: \(error)")
                    currentTextBlock.append(attributedParagraphCopy)
                }
                
                // Add a newline with custom size after each paragraph, except for the last one
                if index < paragraphs.count - 1 {
                    let newlineStyle = NSMutableParagraphStyle()
                    newlineStyle.paragraphSpacing = 0
                    let newlineAttributes: [NSAttributedString.Key: Any] = [
                        .font: NSFont.systemFont(ofSize: 1), // Adjust this size to control spacing
                        .paragraphStyle: newlineStyle
                    ]
                    
                    // Determine the appropriate newline string
                    let newlineString: String
                    if paragraph.hasSuffix("\n") {
                        newlineString = ""
                    } else {
                        newlineString = "\n"
                    }
                    
                    let attributedNewline = NSAttributedString(string: newlineString, attributes: newlineAttributes)
                    currentTextBlock.append(attributedNewline)
                }
            }
        }
        
        appendCurrentTextBlock()
        
        self.parsedContent = parsedContent
    }
    
    
    private func applyMarkdownFormatting(to attributedString: NSMutableAttributedString) throws {
        do {
            try applyTitleFormatting(to: attributedString)
            try applyBoldItalicFormatting(to: attributedString)
            try applyBoldFormatting(to: attributedString)
            try applyItalicFormatting(to: attributedString)
            try applyStrikethroughFormatting(to: attributedString)
            try applyLinkFormatting(to: attributedString)
            try applyListFormatting(to: attributedString)
            try applyQuoteFormatting(to: attributedString)
            try applyInlineCodeFormatting(to: attributedString)
        } catch {
            throw error
        }
    }
}

struct CodeBlockView: View {
    let code: String
    let language: String?
    let defaultFontSize: CGFloat    @State private var copied = false
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            HStack {
                Text(language ?? "plain text")
                    .font(.system(.caption, design: .monospaced))
                    .fontWeight(.semibold)
                
                Spacer()
                
                Button(action: {
                    NSPasteboard.general.clearContents()
                    NSPasteboard.general.setString(code, forType: .string)
                    copied = true
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                        copied = false
                    }
                }) {
                    HStack {
                        Text(copied ? "Copied" : "Copy")
                            .font(.system(.caption, design: .monospaced))
                            .fontWeight(.semibold)
                        
                        Image(systemName: copied ? "checkmark" : "doc.on.doc")
                            .font(.system(size: copied ? 14 : 12))
                    }
                }
                .buttonStyle(PlainButtonStyle())
                .frame(height: 16)
            }
            .padding(.horizontal)
            .padding(.vertical, 8)
            
            Divider()
            
            ScrollView(.horizontal, showsIndicators: false) {
                CodeText(code)
                    .textSelection(.enabled)
                    .font(.system(size: defaultFontSize-1))
            }
        }
        .background(Color(NSColor.textBackgroundColor))
        .cornerRadius(8)
        .overlay(
            RoundedRectangle(cornerRadius: 8)
                .stroke(Color(NSColor.separatorColor), lineWidth: 1)
        )
        .padding(0)
    }
}So I have this code, what I want to do is actually to modify this as you see when there will be a long draw a long block of code streaming you will not show anything and then all of a sudden when it sees the second triple back quote it will end and generate the code block what I want to do is actually add the code block as soon as possible and then add content to that so you probably need to change the codeblock view so that its content can be editable. Make sure that there are multiple, there can be multiple rounds of multiple number of code blocks there and then also you probably need to update the parse markdown function to make sure you add the code block at the first instance, something like that. So figure this out. First, think, plan out, then reflect on your thinking multiple times if you need. Then you come up with the Sulu algorithm without coding it and then finally give the code. So that's the drill you have to go through.