"""
Sends an email the moment an arb opportunity is found.
Uses Gmail SMTP by default - works with any SMTP provider if you change config.
"""

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

import config
from arb import ArbOpportunity


def format_arb_email(opportunity: ArbOpportunity, total_stake: float, legs_with_amounts: list) -> str:
    lines = [
        f"Arb found: {opportunity.home_team} vs {opportunity.away_team}",
        f"Market: {opportunity.market}",
        f"Guaranteed profit margin: {opportunity.profit_margin_percent}%",
        "",
        f"Suggested stake split (total stake: {total_stake}):",
    ]
    for leg in legs_with_amounts:
        lines.append(
            f"  - {leg['outcome'].upper()} on {leg['bookmaker']}: "
            f"odds {leg['odds']}, stake {leg['stake_amount']} "
            f"({leg['stake_percent']}%)"
        )
    lines.append("")
    lines.append("Place both/all legs as soon as possible - odds may move.")
    return "\n".join(lines)


def send_email_alert(subject: str, body: str):
    if not config.EMAIL_APP_PASSWORD:
        print("[alert] EMAIL_APP_PASSWORD not set - skipping email, printing instead:\n")
        print(f"Subject: {subject}\n{body}")
        return

    msg = MIMEMultipart()
    msg["From"] = config.EMAIL_SENDER
    msg["To"] = config.EMAIL_RECIPIENT
    msg["Subject"] = subject
    msg.attach(MIMEText(body, "plain"))

    with smtplib.SMTP(config.SMTP_HOST, config.SMTP_PORT) as server:
        server.starttls()
        server.login(config.EMAIL_SENDER, config.EMAIL_APP_PASSWORD)
        server.send_message(msg)

    print(f"[alert] Email sent: {subject}")
