#!/usr/bin/env python3
"""Update Memory Usage Over Time charts with actual data from timeline files."""

import os
import re
from pathlib import Path

# Languages with Memory Usage Over Time charts
LANGUAGES = {
    "C": {"max_time": 12, "max_memory": 1},
    "Rust": {"max_time": 12, "max_memory": 1},
    "Assembly": {"max_time": 20, "max_memory": 1},
    "Haskell": {"max_time": 8, "max_memory": 12},
    "Dart": {"max_time": 12, "max_memory": 11},
    "Elixir": {"max_time": 300, "max_memory": 3},
    "TypeScript": {"max_time": 1500, "max_memory": 3},
    "Scala": {"max_time": 360, "max_memory": 3},
    "JavaScript": {"max_time": 500, "max_memory": 3},
}

def get_memory_timeline(lang_dir):
    """Get memory timeline from timeline files."""
    timeline_dir = Path(f"timelines/{lang_dir}")
    if not timeline_dir.exists():
        return []
    
    # Read first timeline file
    tsv_file = timeline_dir / "run_1.tsv"
    if not tsv_file.exists():
        return []
    
    memories = []
    with open(tsv_file, 'r') as f:
        for line in f:
            parts = line.strip().split()
            if len(parts) >= 2:
                try:
                    memory_bytes = int(parts[1])
                    # Convert to MB
                    memory_mb = memory_bytes / (1024 * 1024)
                    memories.append(round(memory_mb, 1))
                except ValueError:
                    continue
    
    return memories

def update_readme():
    """Update README with actual memory timeline data."""
    with open('README.md', 'r') as f:
        content = f.read()
    
    for lang, config in LANGUAGES.items():
        # Get memory timeline
        memories = get_memory_timeline(lang)
        
        if not memories:
            print(f"No timeline data for {lang}")
            continue
        
        # Find and replace memory chart
        # Pattern to match the line chart values
        pattern = rf'(title "{lang} - Memory Usage Over Time".*?line \[).*?(\])'
        
        # Create new values string
        values_str = ', '.join(map(str, memories))
        replacement = f'\\g<1>{values_str}\\g<2>'
        
        # Update content
        new_content = re.sub(pattern, replacement, content, flags=re.DOTALL)
        
        if new_content != content:
            content = new_content
            print(f"Updated {lang} with {len(memories)} memory values: {memories[:5]}...")
        else:
            print(f"No match found for {lang}")
    
    # Write updated README
    with open('README.md', 'w') as f:
        f.write(content)
    
    print("\nUpdated README with actual memory timeline data")

if __name__ == "__main__":
    update_readme()