correct the Unindent error: def create_default_config(self):
       """Create default configuration file"""
       doc = tomlkit.document()
       
       merger = tomlkit.table()
       merger.add("status", "running")
       merger.add("mode", "fastest")
       merger.add("specific_subreddit", "AmItheAsshole+relationship_advice+confession+tifu")
       merger.add("check_interval", 3)
       merger.add("target_duration", 10)
       merger.add("auto_process", True)
       doc.add("merger", merger)
       
       paths = tomlkit.table()
       paths.add("source_folder", r"C:\Users\buggy\Desktop\FullyAutomatedRedditVideoMakerBot-main\results")
       paths.add("merge_folder", "MergeVideo")
       doc.add("paths", paths)
       
       processing = tomlkit.table()
       processing.add("delete_source", False)
       processing.add("output_format", "mp4")
       processing.add("safe_mode", True)
       processing.add("finish_current_before_pause", True)
       doc.add("processing", processing)
       
       with open("config.toml", "w", encoding="utf-8") as f:
           f.write(tomlkit.dumps(doc))

   def find_video_pairs(self, subreddit_folder):
       """Find matching pairs of videos (_out.mp4 and .mp4) in a subreddit folder"""
       try:
           folder_path = os.path.join(self.results_folder, subreddit_folder)
           print_step(f"Scanning folder: {folder_path}")

           if not os.path.exists(folder_path):
               print_substep(f"Folder not found: {folder_path}")
               return {}, 0

           video_pairs = {}
           total_duration = 0

           # First find all subtitled versions (_out.mp4) and get their durations
           for file in os.listdir(folder_path):
               if file.endswith('_out.mp4'):  # Only look for subtitled versions
                   base_name = file.replace('_out.mp4', '')

                   if base_name not in video_pairs:
                       video_pairs[base_name] = {
                           'normal': None,
                           'subtitled': None,
                           'duration': 0
                       }

                   full_path = os.path.join(folder_path, file)
                   video_pairs[base_name]['subtitled'] = full_path
                   duration = self.get_video_duration(full_path)
                   video_pairs[base_name]['duration'] = duration
                   total_duration += duration

           # Now find matching normal versions
           for file in os.listdir(folder_path):
               if file.endswith('.mp4') and not file.endswith('_out.mp4'):
                   base_name = file.replace('.mp4', '')
                   if base_name in video_pairs:
                       video_pairs[base_name]['normal'] = os.path.join(folder_path, file)

           # Print found pairs and total duration
           print_step(f"Found video pairs in {subreddit_folder}:")
           complete_pairs = 0
           for base_name, pair in video_pairs.items():
               if pair['normal'] and pair['subtitled']:
                   complete_pairs += 1
                   print_substep(f"Pair {complete_pairs}: {base_name}")
                   print_substep(f" Normal: {os.path.basename(pair['normal'])}")
                   print_substep(f" Subtitled: {os.path.basename(pair['subtitled'])}")
                   print_substep(f" Duration: {pair['duration']:.2f} seconds")

           print_substep(f"Total complete pairs: {complete_pairs}")
           print_substep(f"Total duration: {total_duration:.2f} seconds")

           return video_pairs, total_duration

       except Exception as e:
           print_substep(f"Error scanning folder: {str(e)}")
           return {}, 0

   def detect_template_change(self, video_path):
       """Detect when the title template disappears"""
       try:
           cap = cv2.VideoCapture(video_path)
           if not cap.isOpened():
               print_substep("Could not open video file")
               return 5.0
               
           fps = cap.get(cv2.CAP_PROP_FPS)
           if fps <= 0:
               print_substep("Invalid FPS")
               return 5.0
           
           # Get first frame (which has title)
           ret, first_frame = cap.read()
           if not ret or first_frame is None:
               print_substep("Could not read first frame")
               return 5.0
           
           try:
               # Convert to grayscale
               prev_frame = cv2.cvtColor(first_frame, cv2.COLOR_BGR2GRAY)
           except Exception as e:
               print_substep(f"Error converting frame: {str(e)}")
               return 5.0
               
           frame_count = 0
           
           while True:
               ret, frame = cap.read()
               if not ret or frame is None:
                   break
                   
               try:
                   # Convert current frame to grayscale
                   curr_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                   
                   # Calculate difference between frames
                   diff = cv2.absdiff(curr_frame, prev_frame)
                   
                   # If we detect a significant change
                   mean_diff = np.mean(diff)
                   if mean_diff > 50:  # Threshold value
                       time_point = frame_count / fps
                       print_substep(f"Detected template change at: {time_point:.2f}s")
                       return time_point
                       
                   prev_frame = curr_frame
                   frame_count += 1
                   
               except Exception as e:
                   print_substep(f"Error processing frame {frame_count}: {str(e)}")
                   continue
                   
       except Exception as e:
           print_substep(f"Error in template detection: {str(e)}")
           return 5.0
           
       finally:
           if 'cap' in locals():
               cap.release()
               
       print_substep("No clear template change detected, using default")
       return 5.0

   def find_best_combination(self):
       """Find best combination of videos for target duration"""
       available_pairs = []
       total_duration = 0

       target_minutes = self.target_duration / 60
       print_step(f"\nTarget Duration: {target_minutes:.1f} minutes ({self.target_duration:.0f} seconds)")

       for subreddit in os.listdir(self.results_folder):
           if os.path.isdir(os.path.join(self.results_folder, subreddit)):
               pairs, _ = self.find_video_pairs(subreddit)
               for name, pair in pairs.items():
                   if pair['normal'] and pair['subtitled']:
                       if name not in self.processed_videos:
                           available_pairs.append({
                               'name': name,
                               'subreddit': subreddit,
                               'duration': pair['duration'],
                               'files': pair
                           })

       if not available_pairs:
           print_step("No unprocessed videos found!")
           return None

       available_pairs.sort(key=lambda x: x['duration'], reverse=True)
       selected_pairs = []
       current_duration = 0

       for pair in available_pairs:
           selected_pairs.append(pair)
           current_duration += pair['duration']
           print_substep(f"\nAdded: {pair['name']} ({pair['duration']:.2f}s) from {pair['subreddit']}")
           print_substep(f"Current total duration: {current_duration:.2f}s")
           
           if current_duration >= self.target_duration:
               print_substep("Reached or exceeded target duration")
               break

       if selected_pairs:
           print_substep(f"\nFinal compilation stats:")
           print_substep(f"Duration: {current_duration:.2f}s ({current_duration/60:.1f} minutes)")
           return selected_pairs

       return None

   def process_specific_folder(self):
       """Process videos from specific folder"""
       subreddit = self.config['merger']['specific_subreddit']
       print_step(f"Processing specific folder: {subreddit}")

       pairs, duration = self.find_video_pairs(subreddit)
       if not pairs:
           print_step("No videos found in specified folder!")
           return None

       selected_pairs = []
       current_duration = 0

       for name, pair in pairs.items():
           if name not in self.processed_videos and pair['normal'] and pair['subtitled']:
               if current_duration + pair['duration'] <= self.target_duration:
                   selected_pairs.append({
                       'name': name,
                       'subreddit': subreddit,
                       'duration': pair['duration'],
                       'files': pair
                   })
                   current_duration += pair['duration']

       if selected_pairs:
           return selected_pairs

       return None

   def process_videos(self):
       """Process videos based on current mode"""
       if self.check_config_changed():
           if self.config['processing'].get('safe_mode', True):
               print_step("Config changed during operation. Restarting process...")
               return None

       mode = self.config['merger']['mode']
       if mode == "fastest":
           return self.find_best_combination()
       elif mode == "specific":
           return self.process_specific_folder()
       else:
           print_step(f"Unknown mode: {mode}")
           return None

   def splice_video(self, video_pair):
       """Create spliced version with clean intro and main content"""
       clean_video = None
       subtitled_video = None
       intro_clip = None
       main_clip = None
       
       try:
           print_substep(f"Processing video: {video_pair['name']}")
           print_substep("Loading videos... ⏳")
           
           # Load videos and verify they're valid
           clean_video = VideoFileClip(video_pair['files']['normal'])
           if clean_video is None or clean_video.duration == 0:
               print_substep("❌ Invalid clean video")
               return None

           subtitled_video = VideoFileClip(video_pair['files']['subtitled'])
           if subtitled_video is None or subtitled_video.duration == 0:
               print_substep("❌ Invalid subtitled video")
               return None

           print_substep("✅ Videos loaded successfully")

           # Get title end point and ensure it's valid
           print_substep("Detecting title end point... ⏳")
           title_end = self.detect_template_change(video_pair['files']['normal'])
           print_substep(f"✅ Title ends at: {title_end:.2f}s")
           
           # Ensure title_end is within valid range
           title_end = min(title_end, clean_video.duration - 1)
           title_end = max(title_end, 0)
           
           try:
               print_substep("Creating clips... ⏳")
               intro_clip = clean_video.subclip(0, title_end)
               main_clip = subtitled_video.subclip(title_end)
               
               # Verify clips are valid
               if intro_clip.duration == 0 or main_clip.duration == 0:
                   print_substep("❌ Invalid clip durations")
                   return None
                   
               # Verify frames can be accessed
               _ = intro_clip.get_frame(0)
               _ = main_clip.get_frame(0)
               
               print_substep("✅ Clips created successfully")
               
               # Create final clip
               print_substep("Merging clips... ⏳")
               final = concatenate_videoclips([intro_clip, main_clip], method="compose")
               if final is None or final.duration == 0:
                   print_substep("❌ Failed to create final clip")
                   return None
                   
               print_substep("✅ Video processed successfully")
               return final
               
           except Exception as e:
               print_substep(f"❌ Error creating clips: {str(e)}")
               return None
               
       except Exception as e:
           print_substep(f"❌ Error in video splicing: {str(e)}")
           return None
           
       finally:
           # Clean up all resources
           print_substep("Cleaning up resources... ⏳")
           for clip in [clean_video, subtitled_video, intro_clip, main_clip]:
               if clip is not None:
                   try:
                       clip.close()
                   except:
                       pass
           print_substep("✅ Cleanup complete")

   def write_video_with_progress(self, clip, output_path):
       """Write video file with custom progress tracking"""
       total_frames = int(clip.duration * clip.fps)
       frame_count = [0]  # Use list to allow modification in callback
       
       def progress_callback(current_frame):
           frame_count[0] = current_frame
           progress = (current_frame / total_frames) * 100
           bar_length = 30
           filled = int(bar_length * progress / 100)
           bar = '=' * filled + ' ' * (bar_length - filled)
           print_substep(f"\rProgress: [{bar}] {progress:.1f}%")
       
       clip.write_videofile(
           output_path,
           codec='libx264',
           audio_codec='aac',
           temp_audiofile='temp-audio.m4a',
           remove_temp=True,
           threads=4,
           logger=None,
           write_logfile=False,
           callback=progress_callback
       )

   def merge_videos(self, selected_videos):
       """Merge selected videos with proper splicing"""
       processed_clips = []
       final_clip = None
       total_videos = len(selected_videos)
       
       try:
           print_step("\nStarting video processing phase...")
           for index, video in enumerate(selected_videos, 1):
               print_substep(f"Processing video {index}/{total_videos}: {video['name']}")
               print_substep(f"Progress: [{index * '=' + (total_videos-index) * ' '}] {(index/total_videos)*100:.1f}%")
               
               clip = self.splice_video(video)
               if clip is not None:
                   processed_clips.append(clip)
                   print_substep(f"✅ Successfully processed: {video['name']}")
               else:
                   print_substep(f"❌ Failed to process: {video['name']}")
           
           if not processed_clips:
               print_step("❌ No valid clips to merge")
               return None
           
           print_step(f"Merging {len(processed_clips)} clips... ⏳")
           final_clip = concatenate_videoclips(processed_clips, method="compose")
           
           output_path = os.path.join(
               self.merge_folder,
               f"compilation_{time.strftime('%Y%m%d_%H%M%S')}.mp4"
           )
           
           print_step("Writing final video... ⏳")
           self.write_video_with_progress(final_clip, output_path)
           print_step("✅ Video compilation complete!")
           return output_path
           
       except Exception as e:
           print_step(f"❌ Error in video merging: {str(e)}")
           return None
           
       finally:
           # Clean up all clips
           if final_clip is not None:
               try:
                   final_clip.close()
               except:
                   pass
           for clip in processed_clips:
               try:
                   clip.close()
               except:
                   pass

def main():
   compiler = VideoCompiler()
   print_step("Monitoring for config changes...")
   print_substep("You can modify config.toml at any time to change settings")
   print_substep("Set status to 'paused' to pause, 'running' to resume, or 'stopping' to stop")

   first_run = True

   while True:
       try:
           print_step("\n📂 Starting scan phase...")
           if not compiler.check_status():
               print_step("Stopping process...")
               break

           compiler.check_config_changed()
           if not compiler.config['merger']['auto_process']:
               print_step("Auto-processing disabled in config. Exiting.")
               break

           selected_videos = compiler.process_videos()

           if selected_videos:
               print_step("\n📋 Videos Selected for Compilation:")
               total_duration = 0
               for video in selected_videos:
                   print_substep(f"Video: {video['name']}")
                   print_substep(f"From: {video['subreddit']}")
                   print_substep(f"Duration: {video['duration']:.2f} seconds")
                   print_substep("-" * 50)
                   total_duration += video['duration']

               if total_duration < compiler.target_duration:
                   print_step(f"⚠️ Still need {(compiler.target_duration - total_duration):.2f}s to reach target")
                   
               print_step(f"📊 Total Compilation Duration: {total_duration:.2f} seconds")

               print_step("\n🎬 Starting video processing phase...")
               output_path = compiler.merge_videos(selected_videos)
               
               if output_path:
                   print_step(f"✅ Successfully created compilation: {output_path}")
                   for video in selected_videos:
                       compiler.processed_videos.append(video['name'])
                   compiler.save_processed_videos()

               print_step("\n⌛ Video processing complete. Resuming monitoring...")

               if not first_run:
                   check_interval = compiler.config['merger']['check_interval']
                   print_step(f"\n⏳ Waiting {check_interval} minutes before next scan...")
                   if not compiler.wait_with_status_check(check_interval):
                       break
               else:
                   first_run = False
           else:
               print_step("❌ Not enough unprocessed videos for compilation.")
               check_interval = compiler.config['merger']['check_interval']
               print_step(f"\n⏳ Waiting {check_interval} minutes before next scan...")
               if not compiler.wait_with_status_check(check_interval):
                   break

       except Exception as e:
           print_step(f"❌ Error occurred: {str(e)}")
           print_step("⏳ Waiting 5 minutes before retrying...")
           if not compiler.wait_with_status_check(5):
               break

if __name__ == "__main__":
   main(), Unindent amount does not match previous indent