import os
import re

def fix_section_file(file_path, section_name):
    # Read the content of the section overview file
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # List all files in the section directory
    dir_path = os.path.dirname(file_path)
    files = [f for f in os.listdir(dir_path) if f.endswith('.md') and f != os.path.basename(file_path)]
    
    # Create content with proper links
    new_content = f"""# {section_name}

## Available Documentation

"""
    
    # Add links to all other files in the section
    for file in sorted(files):
        # Get the title from the file
        with open(os.path.join(dir_path, file), 'r', encoding='utf-8') as f:
            file_content = f.read()
            # Try to extract title from first heading
            title_match = re.search(r'#\s+([^\n]+)', file_content)
            if title_match:
                title = title_match.group(1)
            else:
                # Use filename as title if no heading found
                title = file.replace('.html.md', '').replace('-', ' ')
        
        # Add link
        new_content += f"* [{title}]({file})\n"
    
    # Write the updated content
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(new_content)

def fix_all_sections():
    sections = {
        'cloud/cloud.html.md': 'Cloud Services',
        'datavolume/datavolume.html.md': 'Data Volume Management',
        'kubernetes/kubernetes.html.md': 'Kubernetes',
        'networking/networking.html.md': 'Networking',
        'openstackcli/openstackcli.html.md': 'OpenStack CLI',
        'openstackdev/openstackdev.html.md': 'OpenStack Development',
        's3/s3.html.md': 'S3 Storage',
        'windows/windows.html.md': 'Windows Management'
    }
    
    base_dir = "/Users/dhanraj/Desktop/kpme_scraper/docs"
    for rel_path, section_name in sections.items():
        full_path = os.path.join(base_dir, rel_path)
        print(f"Processing {rel_path}...")
        fix_section_file(full_path, section_name)

if __name__ == "__main__":
    fix_all_sections()
