from ftplib import FTP
import os
import imaplib
import email
from email.header import decode_header
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime


# Email account credentials
username = "technical.data@cs-introspectltd.com"  # Replace with your email
password = "User2025$"  # Replace with your password

# Create a Downloads folder if it doesn't exist
downloaded_folder = "C:\\wamp64\\www\\abinc\\2023\\introspect\\dynamic"
downloaded_folder = "/home/intros10/public_html/introspect/uploads"



# Get current date and time strings
now = datetime.now()
date_str = now.strftime('%Y-%m-%d')
time_str = now.strftime('%H-%M')

# Create new path with date and time
downloaded_folder = os.path.join(downloaded_folder, date_str, time_str)


# Ensure the folder exists
os.makedirs(downloaded_folder, exist_ok=True)


# Connect to the mail server
mail = imaplib.IMAP4_SSL('mail.cs-introspectltd.com',
                         993)  # Change for your provider (e.g., imap.mail.yahoo.com for Yahoo)
mail.login(username, password)

# Select the mailbox you want to check
mail.select("inbox")  # Use "inbox" or any folder you want to check for attachments

# List of subjects to search for
subjects = [
    "Huawei IHS Airtel Alarms",
    "Huawei IHS MTN Alarms",
    "RTN Daily CA Performance Update",
    "PW IHS Alarms",
    "Availability Report"
]

# Loop through each subject and process the latest email
for subject in subjects:
    # Search for emails with the given subject
    search_query = f'(SUBJECT "{subject}")'
    status, messages = mail.search(None, search_query)

    # Check if emails are found
    if messages[0]:
        message_ids = messages[0].split()

        # Fetch the latest email ID (the last one in the list)
        latest_email_id = message_ids[-1]

        # Fetch the latest email
        status, msg_data = mail.fetch(latest_email_id, "(RFC822)")

        # Parse the email content
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_bytes(response_part[1])

                # Get the subject and sender of the email
                email_subject, encoding = decode_header(msg["Subject"])[0]
                if isinstance(email_subject, bytes):
                    email_subject = email_subject.decode(encoding if encoding else "utf-8")
                print(f"Subject: {email_subject}")

                from_ = msg.get("From")
                print(f"From: {from_}")

                # If the email message is multipart (contains attachments)
                if msg.is_multipart():
                    for part in msg.walk():
                        # Extract attachment if it exists
                        content_disposition = str(part.get("Content-Disposition"))
                        if "attachment" in content_disposition:
                            filename = part.get_filename()
                            if filename:
                                # Decode the filename if needed
                                filename, encoding = decode_header(filename)[0]
                                if isinstance(filename, bytes):
                                    filename = filename.decode(encoding if encoding else "utf-8")

                                # Save the attachment to the Downloads folder
                                attachment_path = os.path.join(downloaded_folder, filename)
                                with open(attachment_path, "wb") as f:
                                    f.write(part.get_payload(decode=True))
                                print(f"Attachment saved as: {attachment_path}")
                else:
                    print("No attachments found.")
        print("-" * 40)  # Separator between emails
    else:
        print(f"No emails found with subject '{subject}'.")

# Logout from the mail server
mail.logout()


# Email account credentials
username = "technical.data@cs-introspectltd.com"  # Replace with your email
password = "User2025$"  # Replace with your password

# Create a Downloads folder if it doesn't exist

# Connect to the mail server
mail = imaplib.IMAP4_SSL('mail.cs-introspectltd.com', 993 )  # Change for your provider (e.g., imap.mail.yahoo.com for Yahoo)
mail.login(username, password)

# Select the mailbox you want to check
mail.select("inbox")  # Use "inbox" or any folder you want to check for tables

# Search for emails with the specific subject
status, messages = mail.search(None, 'SUBJECT', '"RaaS Outages"')

# Get the latest email (you can change this to filter by specific criteria)
message_ids = messages[0].split()
latest_email_id = message_ids[-1]

# Fetch the email by ID
status, msg_data = mail.fetch(latest_email_id, "(RFC822)")

# Parse the email content
for response_part in msg_data:
    if isinstance(response_part, tuple):
        msg = email.message_from_bytes(response_part[1])

        # Get the subject and sender (optional)
        subject, encoding = decode_header(msg["Subject"])[0]
        if isinstance(subject, bytes):
            subject = subject.decode(encoding if encoding else "utf-8")
        print(f"Subject: {subject}")

        from_ = msg.get("From")
        print(f"From: {from_}")

        # If the email message is multipart (contains HTML body)
        if msg.is_multipart():
            for part in msg.walk():
                # Check if the part is text/html (usually the table is in HTML format)
                if part.get_content_type() == "text/html":
                    html_content = part.get_payload(decode=True).decode()
                    # Parse the HTML content using BeautifulSoup
                    soup = BeautifulSoup(html_content, "html.parser")

                    # Extract the first table found in the email
                    table = soup.find("table")
                    if table:
                        # Parse the table into a pandas DataFrame
                        df = pd.read_html(str(table))[0]

                        # Save the DataFrame as a CSV file in the Downloads folder
                        filename = "ATCRaas.csv"
                        table_path = os.path.join(downloaded_folder, filename)
                        df.to_csv(table_path, index=False)

                        print(f"Table saved as: {table_path}")
                    else:
                        print("No table found in the email.")
        else:
            print("No HTML part found in the email.")

# Logout from the mail server
mail.logout()