import os
import sys
 
# Only run if explicitly forced or in CI environment
IS_CI = os.getenv('CI') == 'true' or os.getenv('CF_PAGES') == '1'
FORCE_RUN = len(sys.argv) > 1 and sys.argv[1] == '--force'
 
if not (IS_CI or FORCE_RUN):
    print("SAFETY LOCK ENGAGED.")
    print("This script destroys code. It typically runs in a CI environment.")
    print("To run locally (and lose your data), use: python redact.py --force")
    sys.exit(1)
 
UNSAFE_FOLDERS = {'daa', 'dbms_est', 'dl', 'ml', 'msp', 'oops', 'os', 'emb', 'cloud'}
# Folders to completely ignore (Optimization)
IGNORE_DIRS = {'.git', '.obsidian', '.vscode', '.vim', 'node_modules', '.quartz', 'Excalidraw', 'quartz-builder'}
TARGET_EXTENSIONS = {'.md', '.cpp', '.py', '.java', '.rs', '.c', '.go', '.js', '.ts', '.cc'}
 
def fast_redact():
    print("Starting Redaction & Conversion...")
    
    for root, dirs, files in os.walk(".", topdown=True):
        dirs[:] = [d for d in dirs if d not in IGNORE_DIRS]
        
        path_parts = root.split(os.sep)
        
        # Check if we are in a sensitive folder
        is_unsafe = not set(path_parts).isdisjoint(UNSAFE_FOLDERS)
 
        for file in files:
            name, ext = os.path.splitext(file)
            
            # If it's a code file, we MUST rename it to .md to make it visible
            if ext in TARGET_EXTENSIONS:
                original_path = os.path.join(root, file)
                new_path = os.path.join(root, file + ".md") # e.g. main.cpp.md
                
                try:
                    # 1. Rename the file
                    os.rename(original_path, new_path)
                    
                    # 2. If Unsafe: Overwrite content
                    if is_unsafe:
                        with open(new_path, 'w') as f:
                             f.write(f"# {file}\n\n> [!WARNING] Private Content\n> 🔒 Source hidden for academic integrity.")
                    
                    # 3. If Safe (e.g. LeetCode): Wrap code in markdown block
                    else:
                        with open(new_path, 'r+') as f:
                            content = f.read()
                            f.seek(0, 0)
                            # Remove the dot from extension for syntax highlighting (cpp, py)
                            lang = ext.replace('.', '') 
                            f.write(f"``` {lang}\n{content}\n```")
                            
                except OSError as e:
                    print(f"Error processing {original_path}: {e}")
 
if __name__ == "__main__":
    fast_redact()
    print("Redaction Complete.")