import os
import shutil

def safe_batch_replace():
    target_ext = ".html"
    
    # We use a shorter string for a guaranteed match in case of spaces/hidden characters
    search_trigger = "305 N Main" 
    
    # This is the exact text we want to wipe out
    old_text = "305 N Main Street, Toledo, Oregon USA" 
    new_text = "10563 Pacific Coast Highway. Seal Rock, OR 97376"
    
    print("==================================================")
    print(f"Targeting: Files ending in {target_ext}")
    print(f"Searching subdirectories for: '{search_trigger}'")
    print("==================================================\n")
    
    matched_files = []
    
    # Walk through current directory and ALL subdirectories
    for root, dirs, files in os.walk("."):
        # Skip common hidden or backup folders
        if any(part.startswith('.') or 'backup' in part.lower() for part in root.split(os.sep)):
            continue
            
        # Debug print: This lets you see the script actively digging into folders
        print(f"Scanning directory: {root}")
            
        for file in files:
            if file.endswith(target_ext):
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    # Looser check to see if the address is anywhere in the file
                    if search_trigger in content:
                        matched_files.append(file_path)
                except (UnicodeDecodeError, PermissionError):
                    continue

    print("\n==================================================")
    if not matched_files:
        print("Scan complete. Still 0 matching active .html files found.")
        print("Tip: Check if the text in your HTML files matches exactly (e.g., '305 N. Main' with a period, or different spacing).")
        return

    print(f"Found {len(matched_files)} files to update:")
    for f in matched_files:
        print(f"  - {f}")
    
    choice = input("\nWould 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 files...")
    for file_path in matched_files:
        try:
            # 1. Create backup
            backup_path = file_path + ".bak"
            shutil.copy2(file_path, backup_path)
            
            # 2. Read and replace
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # If the exact full string is there, replace it. 
            # If only the short trigger matches, we target that to ensure it gets updated.
            if old_text in content:
                updated_content = content.replace(old_text, new_text)
            else:
                # Fallback if there was a typo in the trailing text of the original file
                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__":
    safe_batch_replace()
