#!/usr/bin/env python3
"""Extract actual memory values in bytes from timeline files and update README."""

import os
import re
from pathlib import Path

# Language categories
COMPILED = ["Assembly", "C", "C++", "Rust", "Go", "Nim", "Odin", "Fortran", "Swift", "Crystal"]
JIT = ["Java", "CSharp", "Kotlin", "Julia"]
INTERPRETED = ["Python", "Perl", "PHP", "Ruby", "JavaScript"]

# Map directory names to display names
NAME_MAP = {
    "CSharp": "C#",
    "C++": "C++",
}

def get_peak_memory(lang_dir):
    """Get peak memory in bytes from timeline files."""
    timeline_dir = Path(f"timelines/{lang_dir}")
    if not timeline_dir.exists():
        return 0
    
    peak_memory = 0
    for tsv_file in timeline_dir.glob("run_*.tsv"):
        try:
            with open(tsv_file, 'r') as f:
                for line in f:
                    parts = line.strip().split()
                    if len(parts) >= 2:
                        try:
                            memory = int(parts[1])
                            peak_memory = max(peak_memory, memory)
                        except ValueError:
                            continue
        except Exception as e:
            print(f"Error reading {tsv_file}: {e}")
            continue
    
    return peak_memory

def get_avg_memory(lang_dir):
    """Get average memory in bytes from timeline files."""
    timeline_dir = Path(f"timelines/{lang_dir}")
    if not timeline_dir.exists():
        return 0
    
    total_memory = 0
    count = 0
    for tsv_file in timeline_dir.glob("run_*.tsv"):
        try:
            with open(tsv_file, 'r') as f:
                for line in f:
                    parts = line.strip().split()
                    if len(parts) >= 2:
                        try:
                            memory = int(parts[1])
                            total_memory += memory
                            count += 1
                        except ValueError:
                            continue
        except Exception as e:
            print(f"Error reading {tsv_file}: {e}")
            continue
    
    return total_memory // count if count > 0 else 0

def update_readme():
    """Update README with actual memory values in bytes."""
    # Read current README
    with open('README.md', 'r') as f:
        content = f.read()
    
    # Update compiled languages memory chart
    compiled_memories = []
    for lang in COMPILED:
        memory = get_peak_memory(lang)
        compiled_memories.append(memory)
    
    # Find and replace compiled languages memory chart
    pattern = r'(title "Compiled Languages - Memory Usage \(bytes\) at 100 decimals".*?y-axis "Memory \(bytes\)" 0 --> )\d+'
    max_memory = max(compiled_memories) if compiled_memories else 0
    y_max = max(100, max_memory)  # At least 100 bytes scale
    
    replacement = f'\\g<1>{y_max}'
    content = re.sub(pattern, replacement, content)
    
    # Replace memory values in compiled languages chart
    pattern = r'(title "Compiled Languages - Memory Usage \(bytes\) at 100 decimals".*?bar \[).*?(\])'
    values_str = ', '.join(map(str, compiled_memories))
    replacement = f'\\g<1>{values_str}\\g<2>'
    content = re.sub(pattern, replacement, content, flags=re.DOTALL)
    
    # Update JIT languages memory chart
    jit_memories = []
    for lang in JIT:
        memory = get_peak_memory(lang)
        jit_memories.append(memory)
    
    pattern = r'(title "JIT-Compiled Languages - Memory Usage \(bytes\) at 100 decimals".*?y-axis "Memory \(bytes\)" 0 --> )\d+'
    max_memory = max(jit_memories) if jit_memories else 0
    y_max = max(100, max_memory)
    
    replacement = f'\\g<1>{y_max}'
    content = re.sub(pattern, replacement, content)
    
    # Replace memory values in JIT languages chart
    pattern = r'(title "JIT-Compiled Languages - Memory Usage \(bytes\) at 100 decimals".*?bar \[).*?(\])'
    values_str = ', '.join(map(str, jit_memories))
    replacement = f'\\g<1>{values_str}\\g<2>'
    content = re.sub(pattern, replacement, content, flags=re.DOTALL)
    
    # Update interpreted languages memory chart
    interpreted_memories = []
    for lang in INTERPRETED:
        memory = get_peak_memory(lang)
        interpreted_memories.append(memory)
    
    pattern = r'(title "Interpreted Languages - Memory Usage \(bytes\) at 100 decimals".*?y-axis "Memory \(bytes\)" 0 --> )\d+'
    max_memory = max(interpreted_memories) if interpreted_memories else 0
    y_max = max(100, max_memory)
    
    replacement = f'\\g<1>{y_max}'
    content = re.sub(pattern, replacement, content)
    
    # Replace memory values in interpreted languages chart
    pattern = r'(title "Interpreted Languages - Memory Usage \(bytes\) at 100 decimals".*?bar \[).*?(\])'
    values_str = ', '.join(map(str, interpreted_memories))
    replacement = f'\\g<1>{values_str}\\g<2>'
    content = re.sub(pattern, replacement, content, flags=re.DOTALL)
    
    # Write updated README
    with open('README.md', 'w') as f:
        f.write(content)
    
    print("Updated README with actual memory values in bytes:")
    print(f"Compiled: {compiled_memories}")
    print(f"JIT: {jit_memories}")
    print(f"Interpreted: {interpreted_memories}")

if __name__ == "__main__":
    update_readme()