import os
import re
from pathlib import Path

def get_first_title(md_path):
    with open(md_path, 'r', encoding='utf-8') as file:
        for line in file:
            match = re.match(r'^#\s+(.*)', line.strip())
            if match:
                return match.group(1)
    return "Untitled"

def extract_leading_number(filename):
    match = re.match(r'^(\d{1,2})[_\- ]', filename)
    return match.group(1) if match else None

def generate_markdown_table(directory):
    entries = []
    for filename in os.listdir(directory):
        if filename.endswith('.md'):
            number = extract_leading_number(filename)
            if number is None:
                continue  # Skip files without leading number
            filepath = os.path.join(directory, filename)
            title = get_first_title(filepath)
            entries.append((int(number), number, title, filename))
    
    entries.sort(key=lambda x: x[0])

    table = ["| # | Lecture | Slides |", "|:------|:-----|:------|"]
    for _, number, title, filename in entries:
        table.append(f"| {number} | [{title}]({filename}) | [Download slides]({Path(filename).stem}-slides.html?raw=1) |")

    return '\n'.join(table)

def main():
    directory = "./../"  # current directory, or change to any other path
    output_file = directory + "README.md"
    table_md = generate_markdown_table(directory)
    
    with open(output_file, 'a', encoding='utf-8') as f:
        f.write("# Contents\n\n")
        f.write(table_md)
        f.write("\n")

    print(f"Index written to {output_file}")

if __name__ == "__main__":
    main()