import base64
import os.path
import mimetypes
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from datetime import datetime

SCOPES = ["https://www.googleapis.com/auth/gmail.send"]

def create_message_with_attachment(sender, to, subject, message_text, file_path):
    message = MIMEMultipart()
    message["to"] = to
    message["from"] = sender
    message["subject"] = subject

    msg = MIMEText(message_text)
    message.attach(msg)

    content_type, encoding = mimetypes.guess_type(file_path)
    main_type, sub_type = content_type.split("/", 1)

    with open(file_path, "rb") as fp:
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())

    encoders.encode_base64(msg)
    msg.add_header(
        "Content-Disposition", f"attachment; filename={os.path.basename(file_path)}"
    )
    message.attach(msg)

    return {"raw": base64.urlsafe_b64encode(message.as_bytes()).decode()}

flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds = flow.run_local_server(port=0)

service = build("gmail", "v1", credentials=creds)

sender = 'muni.vadlamudi47@gmail.com'
to = ['muni.vadlamudi47@gmail.com','vnswamy6@gmail.com','vikramkambhoji@gmail.com']
subject = f"Daily Buy Report - {datetime.now().strftime('%Y-%m-%d')}"
message_text = "Please check the attached report for daily buy"
file_path = 'C:/Users/muniv/Desktop/Market/marketdata_analysis/Buy_Entry.csv'  # Replace with your attachment file path

# Set the 'to' field directly in the message dictionary
message = create_message_with_attachment(sender, ', '.join(to), subject, message_text, file_path)

try:
    sent_message = (
        service.users().messages().send(userId="me", body=message).execute()
    )
    print(f"Sent message Message Id: {sent_message['id']}")
except HttpError as error:
    print(f"An error occurred: {error}")
