"""System email sending helper. Uses the admin-configured SMTP settings."""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


def send_system_email(to, subject, body_text, body_html=None):
    """Send an email via the system SMTP configuration.

    Returns (success: bool, error: str|None)
    """
    from app.models.settings import AppSettings

    host = AppSettings.get('system_smtp_host', '')
    port = int(AppSettings.get('system_smtp_port', '587'))
    ssl = AppSettings.get_bool('system_smtp_ssl', default=True)
    username = AppSettings.get('system_smtp_username', '')
    password = AppSettings.get('system_smtp_password', '')
    from_addr = AppSettings.get('system_email_from', '') or username

    if not host or not username or not password:
        return False, 'System-Email nicht konfiguriert'

    try:
        if body_html:
            msg = MIMEMultipart('alternative')
            msg.attach(MIMEText(body_text, 'plain', 'utf-8'))
            msg.attach(MIMEText(body_html, 'html', 'utf-8'))
        else:
            msg = MIMEText(body_text, 'plain', 'utf-8')

        msg['From'] = from_addr
        msg['To'] = to
        msg['Subject'] = subject

        if ssl and port == 465:
            server = smtplib.SMTP_SSL(host, port, timeout=10)
        else:
            server = smtplib.SMTP(host, port, timeout=10)
            server.starttls()

        server.login(username, password)
        server.sendmail(from_addr, [to], msg.as_string())
        server.quit()
        return True, None

    except Exception as e:
        return False, str(e)


def notify_share_link_accessed(share_link, file_name, accessor_ip):
    """Notify the share link creator that someone accessed their shared file."""
    from app.models.user import User

    creator = User.query.get(share_link.created_by)
    if not creator or not creator.email:
        return

    subject = f'Mini-Cloud: Zugriff auf geteilte Datei "{file_name}"'
    body = (
        f'Hallo {creator.username},\n\n'
        f'Jemand hat auf deine geteilte Datei zugegriffen:\n\n'
        f'  Datei: {file_name}\n'
        f'  IP-Adresse: {accessor_ip}\n'
        f'  Downloads bisher: {share_link.download_count}\n\n'
        f'Falls du diesen Zugriff nicht erwartet hast, kannst du den '
        f'Freigabe-Link in deiner Mini-Cloud loeschen.\n\n'
        f'Deine Mini-Cloud'
    )
    send_system_email(creator.email, subject, body)


def notify_share_link_upload(share_link, folder_name, filename, filesize, uploader_ip):
    """Notify the share link creator that someone uploaded a file via their shared folder."""
    from app.models.user import User

    creator = User.query.get(share_link.created_by)
    if not creator or not creator.email:
        return

    def _fmt_size(b):
        for u in ['B', 'KB', 'MB', 'GB']:
            if b < 1024:
                return f'{b:.1f} {u}'
            b /= 1024
        return f'{b:.1f} TB'

    subject = f'Mini-Cloud: Neue Datei in geteiltem Ordner "{folder_name}"'
    body = (
        f'Hallo {creator.username},\n\n'
        f'Jemand hat eine Datei in deinen geteilten Ordner hochgeladen:\n\n'
        f'  Ordner: {folder_name}\n'
        f'  Datei: {filename}\n'
        f'  Groesse: {_fmt_size(filesize)}\n'
        f'  IP-Adresse: {uploader_ip}\n\n'
        f'Melde dich in deiner Mini-Cloud an, um die Datei zu sehen.\n\n'
        f'Deine Mini-Cloud'
    )
    send_system_email(creator.email, subject, body)


def notify_file_shared_with_user(file_name, owner_username, target_user):
    """Notify a user that a file/folder was shared with them."""
    if not target_user.email:
        return

    subject = f'Mini-Cloud: "{file_name}" wurde mit dir geteilt'
    body = (
        f'Hallo {target_user.username},\n\n'
        f'{owner_username} hat "{file_name}" mit dir geteilt.\n\n'
        f'Melde dich in deiner Mini-Cloud an, um die Datei zu sehen.\n\n'
        f'Deine Mini-Cloud'
    )
    send_system_email(target_user.email, subject, body)


def notify_calendar_shared(calendar_name, owner_username, target_user, permission):
    """Notify a user that a calendar was shared with them."""
    if not target_user.email:
        return

    perm_text = 'Lesen' if permission == 'read' else 'Lesen und Schreiben'
    subject = f'Mini-Cloud: Kalender "{calendar_name}" wurde mit dir geteilt'
    body = (
        f'Hallo {target_user.username},\n\n'
        f'{owner_username} hat den Kalender "{calendar_name}" mit dir geteilt.\n'
        f'Berechtigung: {perm_text}\n\n'
        f'Melde dich in deiner Mini-Cloud an, um den Kalender zu sehen.\n\n'
        f'Deine Mini-Cloud'
    )
    send_system_email(target_user.email, subject, body)


def notify_contacts_shared(addressbook_name, owner_username, target_user, permission):
    """Notify a user that an address book was shared with them."""
    if not target_user.email:
        return

    perm_text = 'Lesen' if permission == 'read' else 'Lesen und Schreiben'
    subject = f'Mini-Cloud: Adressbuch "{addressbook_name}" wurde mit dir geteilt'
    body = (
        f'Hallo {target_user.username},\n\n'
        f'{owner_username} hat das Adressbuch "{addressbook_name}" mit dir geteilt.\n'
        f'Berechtigung: {perm_text}\n\n'
        f'Melde dich in deiner Mini-Cloud an.\n\n'
        f'Deine Mini-Cloud'
    )
    send_system_email(target_user.email, subject, body)


def notify_password_shared(shareable_type, owner_username, target_user, permission):
    """Notify a user that passwords were shared with them."""
    if not target_user.email:
        return

    type_text = 'Ein Passwort-Ordner' if shareable_type == 'folder' else 'Ein Passwort-Eintrag'
    subject = f'Mini-Cloud: {type_text} wurde mit dir geteilt'
    body = (
        f'Hallo {target_user.username},\n\n'
        f'{owner_username} hat {type_text.lower()} mit dir geteilt.\n'
        f'Berechtigung: {permission}\n\n'
        f'Melde dich in deiner Mini-Cloud an, um die Passwoerter zu sehen.\n\n'
        f'Deine Mini-Cloud'
    )
    send_system_email(target_user.email, subject, body)


def notify_user_created(user, created_by_username):
    """Notify a newly created user about their account."""
    if not user.email:
        return

    subject = 'Mini-Cloud: Dein Konto wurde erstellt'
    body = (
        f'Hallo {user.username},\n\n'
        f'{created_by_username} hat ein Konto fuer dich in der Mini-Cloud erstellt.\n\n'
        f'Benutzername: {user.username}\n\n'
        f'Bitte melde dich an und aendere dein Passwort.\n\n'
        f'Deine Mini-Cloud'
    )
    send_system_email(user.email, subject, body)


def notify_conflict_to_admin(conflict_user, conflict_file_name, conflict_copy_name,
                             folder_path, lock_user_name, lock_user_email, locked_since):
    """Notify admin about a sync conflict (user edited a locked file)."""
    from app.models.settings import AppSettings

    admin_email = AppSettings.get('system_email_from', '')
    if not admin_email:
        return

    subject = f'Mini-Cloud: Datei-Konflikt - {conflict_file_name}'
    body = (
        f'Datei-Konflikt in der Mini-Cloud!\n\n'
        f'Benutzer:         {conflict_user.username}'
        f'{" (" + conflict_user.email + ")" if conflict_user.email else ""}\n'
        f'Hat bearbeitet:   {conflict_file_name}\n'
        f'Ordner:           {folder_path}\n'
        f'Konflikt-Kopie:   {conflict_copy_name}\n\n'
        f'Gesperrt von:     {lock_user_name}'
        f'{" (" + lock_user_email + ")" if lock_user_email else ""}\n'
        f'Gesperrt seit:    {locked_since}\n\n'
        f'Ursache: {conflict_user.username} hat die Datei lokal bearbeitet '
        f'waehrend {lock_user_name} sie ausgecheckt hatte.\n\n'
        f'Die Aenderungen von {conflict_user.username} wurden als '
        f'Konflikt-Kopie gespeichert und muessen manuell zusammengefuehrt werden.\n\n'
        f'Deine Mini-Cloud'
    )
    send_system_email(admin_email, subject, body)
