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

import re
import sys
import os

def convert_headers(text):
    """Convert markdown headers to WhatsApp format"""
    # Convert # Header to **HEADER**
    text = re.sub(r'^#\s+(.+)$', r'**\1**', text, flags=re.MULTILINE)
    text = re.sub(r'^##\s+(.+)$', r'**\1**', text, flags=re.MULTILINE)
    text = re.sub(r'^###\s+(.+)$', r'*\1*', text, flags=re.MULTILINE)
    return text

def convert_tables_to_lists(text):
    """Convert markdown tables to bullet lists"""
    lines = text.split('\n')
    result = []
    in_table = False
    table_rows = []
    
    for line in lines:
        # Detect table start
        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, convert it
            if table_rows:
                result.extend(convert_table(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 file ends with table
    if table_rows:
        result.extend(convert_table(table_rows))
    
    return '\n'.join(result)

def convert_table(rows):
    """Convert a markdown table to bullet list"""
    if not rows:
        return []
    
    # Parse header
    header = rows[0]
    headers = [h.strip() for h in header.split('|') if h.strip()]
    
    converted = []
    
    # Convert each data row
    for row in rows[1:]:
        if '---' in row or '|--' in row:
            continue  # Skip separator row
        
        cells = [c.strip() for c in row.split('|') if c.strip()]
        if len(cells) >= len(headers):
            # Create bullet item
            item_parts = []
            for i in range(min(len(headers), len(cells))):
                if cells[i]:  # Only add if cell has content
                    item_parts.append(f"{headers[i]}: {cells[i]}")
            
            if item_parts:
                converted.append(f"• {' | '.join(item_parts)}")
    
    return converted

def optimize_links(text):
    """Optimize links for WhatsApp"""
    # Convert markdown links to plain URLs or wrapped URLs
    # [text](url) -> url or <url>
    text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'\2', text)
    
    # Wrap multiple consecutive links in <>
    lines = text.split('\n')
    result = []
    for line in lines:
        # Find URLs in line
        urls = re.findall(r'https?://[^\s<>"]+|www\.[^\s<>"]+', line)
        if len(urls) > 1:
            # Wrap each URL in <>
            for url in urls:
                line = line.replace(url, f'<{url}>')
        result.append(line)
    
    return '\n'.join(result)

def format_lists(text):
    """Format lists for WhatsApp"""
    # Convert numbered lists to bullet lists
    text = re.sub(r'^\d+\.\s+', '• ', text, flags=re.MULTILINE)
    # Convert dash lists to bullet lists
    text = re.sub(r'^-\s+', '• ', text, flags=re.MULTILINE)
    # Convert asterisk lists to bullet lists
    text = re.sub(r'^\*\s+', '• ', text, flags=re.MULTILINE)
    return text

def add_visual_separators(text):
    """Add emoji separators for better readability"""
    lines = text.split('\n')
    result = []
    
    for i, line in enumerate(lines):
        result.append(line)
        # Add separator after headers
        if line.strip().startswith('**') and line.strip().endswith('**'):
            if i + 1 < len(lines) and lines[i + 1].strip() != '':
                result.append('')  # Empty line for spacing
    
    return '\n'.join(result)

def convert_to_whatsapp(markdown_text):
    """Convert markdown to WhatsApp format"""
    text = markdown_text
    
    # Apply conversions in order
    text = convert_headers(text)
    text = convert_tables_to_lists(text)
    text = format_lists(text)
    text = optimize_links(text)
    text = add_visual_separators(text)
    
    # Remove excessive blank lines
    text = re.sub(r'\n\s*\n\s*\n', '\n\n', text)
    
    return text.strip()

def main():
    """Main function"""
    if len(sys.argv) < 2:
        print("Usage: python3 convert_to_whatsapp.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
    whatsapp_text = convert_to_whatsapp(markdown_text)
    
    # Output
    if output_file:
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(whatsapp_text)
        print(f"✅ Converted to WhatsApp format: {output_file}")
    else:
        print(whatsapp_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(whatsapp_text)} characters", file=sys.stderr)
    print(f"   Lines: {whatsapp_text.count(chr(10)) + 1}", file=sys.stderr)

if __name__ == "__main__":
    main()