#!/usr/bin/env python3
"""
Convert markdown to Discord-friendly format
"""

import re
import sys
import os

def preserve_code_blocks(text):
    """Ensure code blocks are properly formatted for Discord"""
    # Discord supports ```language\ncode\n``` format
    # We need to ensure code blocks have proper backticks
    
    # Find all code blocks
    lines = text.split('\n')
    result = []
    in_code_block = False
    code_block_lines = []
    code_block_lang = ''
    
    for line in lines:
        if line.strip().startswith('```'):
            if not in_code_block:
                # Start of code block
                in_code_block = True
                code_block_lang = line.strip()[3:].strip() or 'text'
                code_block_lines = []
            else:
                # End of code block
                in_code_block = False
                result.append(f'```{code_block_lang}')
                result.extend(code_block_lines)
                result.append('```')
        elif in_code_block:
            code_block_lines.append(line)
        else:
            result.append(line)
    
    # Handle unclosed code block
    if in_code_block:
        result.append(f'```{code_block_lang}')
        result.extend(code_block_lines)
        result.append('```')
    
    return '\n'.join(result)

def convert_links(text):
    """Convert and optimize links for Discord"""
    # Discord supports [text](url) format
    # Also supports plain URLs and <url> to suppress embeds
    
    # Convert bare URLs to suppress embeds if multiple on same line
    lines = text.split('\n')
    result = []
    
    for line in lines:
        # Find URLs
        urls = re.findall(r'https?://[^\s<>"]+|www\.[^\s<>"]+', line)
        if len(urls) > 1:
            # Wrap each URL in <> to suppress embeds
            for url in urls:
                line = line.replace(url, f'<{url}>')
        elif len(urls) == 1 and '[' not in line and ']' not in line:
            # Single URL without markdown link format
            # Keep as is (Discord will embed it)
            pass
        
        result.append(line)
    
    return '\n'.join(result)

def format_mentions(text):
    """Format Discord mentions properly"""
    # @username -> <@!userid> or <@&roleid>
    # #channel -> <#channelid>
    
    # For now, just ensure @ and # are preserved
    # In a real implementation, you'd need to resolve IDs
    
    return text

def optimize_formatting(text):
    """Optimize markdown formatting for Discord"""
    # Discord uses **bold**, *italic*, __underline__, ~~strikethrough~~
    
    # Ensure consistent bold formatting
    text = re.sub(r'\*\*(.+?)\*\*', r'**\1**', text)
    text = re.sub(r'__(.+?)__', r'__\1__', text)
    text = re.sub(r'\~\~(.+?)\~\~', r'~~\1~~', text)
    
    # Convert _italic_ to *italic* (more consistent)
    text = re.sub(r'\b_(.+?)_\b', r'*\1*', text)
    
    return text

def handle_tables(text):
    """Handle markdown tables for Discord"""
    # Discord doesn't support markdown tables well
    # Convert to code blocks or simple formatting
    
    lines = text.split('\n')
    result = []
    in_table = False
    table_rows = []
    
    for line in lines:
        if '|' in line and '---' not in line and not line.startswith('|--'):
            in_table = True
            table_rows.append(line)
        elif in_table and ('|' not in line or line.strip() == ''):
            # End of table
            if table_rows:
                result.extend(format_table_for_discord(table_rows))
                table_rows = []
            in_table = False
            result.append(line)
        elif in_table:
            table_rows.append(line)
        else:
            result.append(line)
    
    # Handle last table
    if table_rows:
        result.extend(format_table_for_discord(table_rows))
    
    return '\n'.join(result)

def format_table_for_discord(rows):
    """Format table as Discord-friendly text"""
    if not rows:
        return []
    
    # Simple formatting: header row bolded
    formatted = []
    
    # Header
    header = rows[0]
    headers = [h.strip() for h in header.split('|') if h.strip()]
    formatted.append('**' + ' | '.join(headers) + '**')
    
    # Separator
    formatted.append('---')
    
    # Data rows
    for row in rows[1:]:
        if '---' in row or '|--' in row:
            continue
        
        cells = [c.strip() for c in row.split('|') if c.strip()]
        if cells:
            formatted.append(' | '.join(cells))
    
    return formatted

def convert_to_discord(markdown_text):
    """Convert markdown to Discord format"""
    text = markdown_text
    
    # Apply conversions in order
    text = preserve_code_blocks(text)
    text = handle_tables(text)
    text = convert_links(text)
    text = format_mentions(text)
    text = optimize_formatting(text)
    
    return text.strip()

def main():
    """Main function"""
    if len(sys.argv) < 2:
        print("Usage: python3 convert_to_discord.py <input_file> [output_file]")
        print("       or pipe markdown to stdin")
        sys.exit(1)
    
    input_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) > 2 else None
    
    # Read input
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            markdown_text = f.read()
    except FileNotFoundError:
        print(f"Error: File '{input_file}' not found")
        sys.exit(1)
    
    # Convert
    discord_text = convert_to_discord(markdown_text)
    
    # Output
    if output_file:
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(discord_text)
        print(f"✅ Converted to Discord format: {output_file}")
    else:
        print(discord_text)
    
    # Show stats
    print(f"\n📊 Conversion stats:", file=sys.stderr)
    print(f"   Original: {len(markdown_text)} characters", file=sys.stderr)
    print(f"   Converted: {len(discord_text)} characters", file=sys.stderr)
    print(f"   Lines: {discord_text.count(chr(10)) + 1}", file=sys.stderr)

if __name__ == "__main__":
    main()