import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import streamlit as st

def send_auction_notification(status, data):
    SENDER_EMAIL = "dreveniceliptov@gmail.com" 
    APP_PASSWORD = "omnjpydwhbfkrbby"
    APP_URL = "https://dap.e-financials.net/Auctions" # Change to your actual deployed URL
    
    try:
        recipient = data.get('RecipientEmail')
        if not recipient:
            print("Mailer Error: No recipient email address found.")
            return False

        bank = data.get('BankName', 'Financial Institution')
        client = data.get('ClientName', 'Our Client')
        currency = data.get('Currency', '')
        
        # Ensure rates are handled even if keys vary slightly
        rate = data.get('CallRate') or data.get('OfferRate') or '0'
        
        # Safe Amount Formatting
        amt_val = data.get('Amount', 0)
        try:
            amount_formatted = f"{float(amt_val):,.2f}"
        except:
            amount_formatted = str(amt_val)

        # FIX: Added missing comma between BankRejected and ClientRejected
        templates = {
            "Call": {
                "subject": f"Deposit Auction Call - {client}",
                "body": (f"Dear {bank} Team,\n\nPlease find a new deposit request from {client}:\n\n"
                         f"• Client: {client}\n• Amount: {amount_formatted} {currency}\n"
                         f"• Requested Call Time: {data.get('CallTime', 'N/A')}\n"
                         f"• Trade Date: {data.get('TradeDate', 'N/A')}\n"
                         f"• Maturity Date: {data.get('Maturity', 'N/A')}\n"
                         f"• Tenor: {data.get('Tenor', 'N/A')}\n"
                         f"• Target Rate: {rate}% \n\nPlease log in to the portal.\n\nBest regards,\nAuction System"
                         f"\n\nAccess the platform directly: {APP_URL}")
            },
            "Offer": {
                "subject": f"New Deposit Offer - {bank}",
                "body": (f"Dear {client} Team,\n\n{bank} has submitted an offer for your deposit request:\n\n"
                         f"• Amount: {amount_formatted} {currency}\n"
                         f"• Offered Rate: {rate}%\n"
                         f"• Maturity Date: {data.get('Maturity', 'N/A')}\n\n"
                         f"Please log in to the portal to confirm.\n\nBest regards,\nAuction System"
                         f"\n\nAccess the platform directly: {APP_URL}")
            },
            "Active": {
                "subject": f"Deposit Auction Confirmation - {client}",
                "body": (f"Dear {bank} Team,\n\nThe client has ACCEPTED your offer.\n\n"
                         f"• Amount: {amount_formatted} {currency}\n"
                         f"• Confirmed Rate: {rate}%\n"
                         f"• Value Date: {data.get('TradeDate', 'N/A')}\n"
                         f"• Maturity Date: {data.get('Maturity', 'N/A')}\n\nBest regards,\nAuction System"
                         f"\n\nAccess the platform directly: {APP_URL}")
            },
            "BankRejected": {
                "subject": f"Deposit Request Declined - {bank}",
                "body": f"Dear {client} Team,\n\n{bank} is unable to provide an offer for your request of {amount_formatted} {currency} at this time."
            },
            "ClientRejected": {
                "subject": f"Offer Rejected by Client - {client}",
                "body": f"Dear {bank} Team,\n\nThe client has declined your offer of {rate}% for {amount_formatted} {currency}."
            }
        }

        conf = templates.get(status)
        if not conf:
            print(f"Mailer Error: Status '{status}' not found in templates.")
            return False

        msg = MIMEMultipart()
        msg['From'] = SENDER_EMAIL
        msg['To'] = recipient
        msg['Subject'] = conf["subject"]
        msg.attach(MIMEText(conf["body"], 'plain'))

        # SMTP Connection
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(SENDER_EMAIL, APP_PASSWORD)
        server.send_message(msg)
        server.quit()
        
        return True
    except Exception as e:
        st.error(f"Critical Mailer Error: {e}")
        return False