import os
import re

def mask_env_value(line):
    if '=' not in line:
        return line
    key, value = line.split('=', 1)
    value = value.strip()
    if len(value) <= 6:
        masked = '*' * len(value)
    else:
        masked = value[:3] + '*' * (len(value) - 6) + value[-3:]
    return f"{key}={masked}"

def document_project(root_dir, output_file):
    skip_dirs = {'.git', 'vendor', 'node_modules', 'storage', '.gemini'}
    extensions = {'.php', '.js', '.css', '.html', '.sql', '.env', '.json', '.sh'}
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("# Musadaq Project Documentation\n\n")
        f.write("This file contains the complete source code of the project (excluding dependencies and sensitive data).\n\n")
        
        for root, dirs, files in os.walk(root_dir):
            # Skip unwanted directories
            dirs[:] = [d for d in dirs if d not in skip_dirs]
            
            for file in files:
                file_path = os.path.join(root, file)
                rel_path = os.path.relpath(file_path, root_dir)
                
                # Check if file should be included
                _, ext = os.path.splitext(file)
                if ext not in extensions:
                    continue
                
                f.write(f"## File: `{rel_path}`\n\n")
                
                lang = ext.replace('.', '')
                if lang == 'env':
                    lang = 'bash'
                elif lang == 'php':
                    lang = 'php'
                
                f.write(f"```{lang}\n")
                
                try:
                    with open(file_path, 'r', encoding='utf-8') as src:
                        for line in src:
                            if ext == '.env':
                                f.write(mask_env_value(line) + "\n")
                            else:
                                f.write(line)
                except Exception as e:
                    f.write(f"// Error reading file: {e}\n")
                
                f.write("\n```\n\n")

if __name__ == "__main__":
    current_dir = os.getcwd()
    output_path = os.path.join(current_dir, "PROJECT_DOCUMENTATION.md")
    print(f"Documenting project in: {current_dir}...")
    document_project(current_dir, output_path)
    print(f"Documentation generated at: {output_path}")
