import os
import shutil

def diagnostic_batch_replace():
    target_ext = ".html"
    
    # Let's use an even simpler, bulletproof trigger based on your grep output
    search_trigger = "305 N Main"
    
    # Exact text from your screenshot to replace
    old_text = "305 N Main Street, Toledo, Oregon USA"
    new_text = "10563 Pacific Coast Highway. Seal Rock, OR 97376"
    
    # Print current working directory so we know exactly where Python is looking
    print("==================================================")
    print(f"CURRENT SCRIPT LOCATION: {os.getcwd()}")
    print(f"Targeting files ending in: '{target_ext}'")
    print(f"Searching for string:     '{search_trigger}'")
    print("==================================================\n")
    
    matched_files = []
    html_file_count = 0
    
    for root, dirs, files in os.walk("."):
        # Skip hidden or backup folders
        if any(part.startswith('.') or 'backup' in part.lower() for part in root.split(os.sep)):
            continue
            
        for file in files:
            if file.endswith(target_ext):
                html_file_count += 1
                file_path = os.path.join(root, file)
                
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    # Diagnostic print for EVERY html file found
                    if search_trigger in content:
                        print(f"[ MATCH FOUND ] -> {file_path}")
                        matched_files.append(file_path)
                    else:
                        # This will help us see if it's reading the file but missing the text
                        print(f"[ SKIPPED (No Match) ] -> {file_path}")
                        
                except Exception as e:
                    print(f"[ ERROR READING ] -> {file_path} Error: {e}")

    print("\n==================================================")
    print(f"DIAGNOSTIC SUMMARY:")
    print(f"Total '.html' files scanned: {html_file_count}")
    print(f"Total files matching trigger: {len(matched_files)}")
    print("==================================================\n")

    if not matched_files:
        print("No files were updated. Check the log above to see if your target directory was scanned.")
        return

    choice = input("Would you like to proceed with creating backups and replacing? (yes/no): ").strip().lower()
    if choice not in ['yes', 'y']:
        print("Process aborted. No files were changed.")
        return

    print("\nProcessing updates...")
    for file_path in matched_files:
        try:
            # 1. Create backup (.html.bak)
            backup_path = file_path + ".bak"
            shutil.copy2(file_path, backup_path)
            
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # Smart replacement: if the full string matches, replace it. 
            # Otherwise, replace just the trigger area to be completely safe.
            if old_text in content:
                updated_content = content.replace(old_text, new_text)
            else:
                updated_content = content.replace(search_trigger, new_text)
            
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(updated_content)
                
            print(f"Successfully updated & backed up: {file_path}")
            
        except Exception as e:
            print(f"Error processing {file_path}: {e}")

    print("\nAll done!")

if __name__ == "__main__":
    diagnostic_batch_replace()
