import mimetypes
import os
import smtplib
from email.message import EmailMessage


class EmailService:
    def __init__(
        self,
        email_user,
        email_app_password,
        smtp_host="smtp.gmail.com",
        smtp_port=465,
        timeout_seconds=10,
        logger=None,
    ):
        self.email_user = email_user
        self.email_app_password = email_app_password
        self.smtp_host = smtp_host
        self.smtp_port = int(smtp_port)
        self.timeout_seconds = timeout_seconds
        self.logger = logger

    def send_participant_results(
        self,
        to_email,
        participant_name,
        app_name,
        score,
        successful_cues,
        timed_out_cues,
        scoreboard_url="",
        attachment_path=None,
    ):
        message = EmailMessage()
        message["Subject"] = f"{participant_name or 'Participant'} - {app_name} Results"
        message["From"] = self.email_user
        message["To"] = to_email

        body_lines = [
            f"Hello {participant_name or 'Participant'},",
            "",
            f"Thanks for playing {app_name}.",
            f"Average reaction time: {score:.2f} seconds",
            f"Successful cues: {successful_cues}",
            f"Timed out cues: {timed_out_cues}",
        ]
        if scoreboard_url:
            body_lines.extend(["", f"Scoreboard: {scoreboard_url}"])

        message.set_content("\n".join(body_lines))

        if attachment_path and os.path.exists(attachment_path):
            mime_type, _ = mimetypes.guess_type(attachment_path)
            maintype, subtype = (mime_type or "application/octet-stream").split("/", 1)
            with open(attachment_path, "rb") as attachment_file:
                message.add_attachment(
                    attachment_file.read(),
                    maintype=maintype,
                    subtype=subtype,
                    filename=os.path.basename(attachment_path),
                )

        with smtplib.SMTP_SSL(
            self.smtp_host, self.smtp_port, timeout=self.timeout_seconds
        ) as smtp:
            smtp.login(self.email_user, self.email_app_password)
            smtp.send_message(message)

        if self.logger:
            self.logger.info(f"Sent Hand Flop results email to {to_email}")
