from pathlib import Path
from datetime import datetime
from collections import defaultdict
import re


def process_build_version(name):
    """Put Build/v and everything after them in brackets and make game name bold"""
    # Handle "Build" pattern
    build_pattern = r'^(.+?)(Build\s*[\d.]+\s*.+)$'
    name = re.sub(build_pattern, lambda m: f'**{m.group(1).strip()}** [{m.group(2)}]', name)
    
    # Handle "v#" pattern (where # is any number)
    version_pattern = r'^(.+?)(v[\d.]+\s*.+)$'
    name = re.sub(version_pattern, lambda m: f'**{m.group(1).strip()}** [{m.group(2)}]', name)
    
    # If no version/build info, make entire name bold
    if '[' not in name:
        name = f'**{name.strip()}**'
    
    return name

def clean_filename(name):
    """Remove -OFME and file extension from filename"""
    name = name.rsplit('.', 1)[0]  # Remove extension
    name = name.replace('-OFME', '')
    
    # Find and temporarily protect version/build number dots
    build_matches = re.finditer(r'Build\s*[\d.]+', name)
    version_matches = re.finditer(r'v[\d.]+', name)
    
    # Replace protected sections with temporary markers
    protected_sections = []
    for match in list(build_matches) + list(version_matches):
        protected_sections.append(match.group(0))
        name = name.replace(match.group(0), f'@@{len(protected_sections)-1}@@')
    
    # Replace remaining dots with spaces
    name = name.replace('.', ' ')
    
    # Restore protected sections
    for i, section in enumerate(protected_sections):
        name = name.replace(f'@@{i}@@', section)
    
    # Process build/version patterns
    name = process_build_version(name)
    return name

def get_file_listing():
    root_dir = Path('.')
    categories = defaultdict(lambda: defaultdict(list))
    
    try:
        # Scan directories, excluding dot folders and root
        for item in root_dir.glob('**/'):
            if item == root_dir or any(part.startswith('.') for part in item.parts):
                continue
                
            if item.is_dir():
                # Split path into main category and subcategory
                parts = item.relative_to(root_dir).parts
                if len(parts) >= 2:
                    main_cat, sub_cat = parts[0], parts[1]
                    
                    # Get files in this directory
                    for file in item.glob('*'):
                        if file.is_file():
                            clean_name = clean_filename(file.name)
                            rel_path = file.relative_to(root_dir).as_posix()
                            categories[main_cat][sub_cat].append((clean_name, rel_path))

        # Generate markdown output
        with open('readme.md', 'w', encoding='utf-8') as f:
            f.write(f'# File Listing\n')
            
            total_files = 0
            for main_cat in sorted(categories.keys()):
                main_count = sum(len(files) for files in categories[main_cat].values())
                f.write(f'## {main_cat} ({main_count})\n')
                
                for sub_cat in sorted(categories[main_cat].keys()):
                    files = categories[main_cat][sub_cat]
                    if files:
                        total_files += len(files)
                        f.write(f'### {sub_cat} ({len(files)})\n')
                        for filename, rel_path in sorted(files):
                            f.write(f'- [{filename}]({rel_path})\n')
                        f.write('\n')
            
            f.write(f'<br><br>\n\n## Info\n- **Generated: {datetime.now().strftime("%Y-%m-%d %H:%M")}**\n')
            f.write(f'- **Total Files: {total_files}**')

    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == '__main__':
    get_file_listing()