import imaplib
import ssl

# Credentials from credentials.php
USER = 'heures@free.fr'
PASS = 'Kidan_@93500'
HOST = 'imap.free.fr'

def main():
    print(f"Connecting to {HOST}...")
    try:
        # Connect with SSL
        mail = imaplib.IMAP4_SSL(HOST)
        print("Logging in...")
        mail.login(USER, PASS)
        print("Logged in successfully!")

        # List all folders
        status, folders = mail.list()
        print("\nFolders available:")
        for f in folders:
            print(f.decode())

        # Possible trash folder names
        possible_trash = ['Trash', 'Corbeille', 'INBOX/Trash', 'Junk', 'Spam']
        total_recovered = 0

        for f_bytes in folders:
            f_str = f_bytes.decode()
            # Folder name is usually in the last part after " " (space)
            folder_name = f_str.split(' "/" ')[-1].strip('"')
            
            should_check = False
            for pt in possible_trash:
                if pt.lower() in folder_name.lower():
                    should_check = True
                    break
            
            if should_check:
                print(f"\nChecking folder: {folder_name}")
                mail.select(f'"{folder_name}"')
                status, messages = mail.search(None, 'ALL')
                
                if status == 'OK' and messages[0]:
                    msg_ids = messages[0].split()
                    print(f"  Found {len(msg_ids)} messages. Moving to INBOX...")
                    for m_id in msg_ids:
                        mail.copy(m_id, 'INBOX')
                        mail.store(m_id, '+FLAGS', '\\Deleted')
                    mail.expunge()
                    total_recovered += len(msg_ids)
                else:
                    print("  No messages found.")

        print(f"\nTotal messages recovered: {total_recovered}")
        mail.logout()
        print("Done.")

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()
