import os
import re
import tkinter as tk
from tkinter import filedialog, messagebox


def find_and_replace_url(directory, current_url, new_url):
    url_pattern = re.compile(r"https?://[^\s]+")
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(".py"):
                file_path = os.path.join(root, file)
                with open(file_path, "r", encoding="utf-8") as f:
                    content = f.read()
                if current_url in content:
                    print(f"URL encontrada em: {file_path}")
                    updated_content = content.replace(current_url, new_url)
                    with open(file_path, "w", encoding="utf-8") as f:
                        f.write(updated_content)
                    print(f"URL atualizada em: {file_path}")


def browse_directory():
    directory = filedialog.askdirectory()
    if directory:
        directory_entry.delete(0, tk.END)
        directory_entry.insert(0, directory)


def update_urls():
    current_url = current_url_entry.get()
    new_url = new_url_entry.get()
    directory = directory_entry.get()
    if not current_url or not new_url or not directory:
        messagebox.showwarning(
            "Entrada Inválida", "Por favor, preencha todos os campos."
        )
        return
    find_and_replace_url(directory, current_url, new_url)
    messagebox.showinfo("Concluído", "URLs atualizadas com sucesso.")


app = tk.Tk()
app.title("Atualizador de URLs")

tk.Label(app, text="URL Atual:").grid(row=0, column=0, padx=10, pady=5)
current_url_entry = tk.Entry(app, width=50)
current_url_entry.grid(row=0, column=1, padx=10, pady=5)

tk.Label(app, text="Nova URL:").grid(row=1, column=0, padx=10, pady=5)
new_url_entry = tk.Entry(app, width=50)
new_url_entry.grid(row=1, column=1, padx=10, pady=5)

tk.Label(app, text="Diretório:").grid(row=2, column=0, padx=10, pady=5)
directory_entry = tk.Entry(app, width=50)
directory_entry.grid(row=2, column=1, padx=10, pady=5)

browse_button = tk.Button(app, text="Procurar", command=browse_directory)
browse_button.grid(row=2, column=2, padx=10, pady=5)

update_button = tk.Button(app, text="Atualizar URLs", command=update_urls)
update_button.grid(row=3, column=1, pady=20)

app.mainloop()
