import re

class SlackFormatter:
    """
    Converts standard Markdown to Slack's mrkdwn format.
    Handles:
    - Bold: **text** -> *text*
    - Links: [text](url) -> <url|text>
    - Headers: # Text -> *Text*
    - Strikethrough: ~~text~~ -> ~text~
    
    Preserves code blocks (```...```) from formatting.
    """
    
    @staticmethod
    def convert(text: str) -> str:
        if not text:
            return ""
            
        # Split by code blocks to avoid formatting code
        # Pattern captures the delimiter so we keep the code block
        parts = re.split(r'(```[\s\S]*?```)', text)
        
        formatted_parts = []
        for i, part in enumerate(parts):
            # Even indices are normal text, Odd indices are code blocks
            if i % 2 == 0:
                formatted_parts.append(SlackFormatter._format_text_segment(part))
            else:
                formatted_parts.append(part) # Keep code block as is
                
        return "".join(formatted_parts)

    @staticmethod
    def _format_text_segment(text: str) -> str:
        # 1. Links: [label](url) -> <url|label>
        # Note: Slack requires <url|label>.
        text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<\2|\1>', text)
        
        # 2. Bold: **text** -> *text*
        text = re.sub(r'\*\*([^*]+)\*\*', r'*\1*', text)
        
        # 3. Headers: ### Text -> *Text*
        # We replace any sequence of # at start of line (or after newline) with bold
        text = re.sub(r'(?m)^#{1,6}\s+(.+)$', r'*\1*', text)
        
        # 4. Strikethrough: ~~text~~ -> ~text~
        text = re.sub(r'~~([^~]+)~~', r'~\1~', text)
        
        return text
