#!/usr/bin/env python3
"""Email alert sender per VPS Hetzner - Mavis 21/07 2026."""
import os
import sys
import smtplib
import logging
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from pathlib import Path

sys.path.insert(0, '/opt/charter-live')
ENV_FILE = Path('/opt/charter-live/.env.alerts')
LOG_FILE = '/opt/charter-live/logs/alert.log'

logging.basicConfig(
    filename=LOG_FILE,
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s'
)
log = logging.getLogger()


def load_config():
    cfg = {}
    if not ENV_FILE.exists():
        log.error(f'Env file mancante: {ENV_FILE}')
        return None
    with open(ENV_FILE) as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#') or '=' not in line:
                continue
            k, v = line.split('=', 1)
            cfg[k.strip()] = v.strip()
    required = ['SMTP_HOST', 'SMTP_PORT', 'SMTP_USER', 'SMTP_PASS', 'ALERT_EMAIL_TO']
    for k in required:
        if k not in cfg or not cfg[k] or cfg[k].startswith('your-'):
            log.warning(f'Config mancante: {k}')
            return None
    return cfg


def send_alert(subject, body, level='INFO'):
    cfg = load_config()
    if not cfg:
        return False
    try:
        msg = MIMEMultipart()
        msg['From'] = cfg['SMTP_USER']
        msg['To'] = cfg['ALERT_EMAIL_TO']
        msg['Subject'] = f'[Charter VPS] [{level}] {subject}'
        msg.attach(MIMEText(body, 'plain'))
        with smtplib.SMTP(cfg['SMTP_HOST'], int(cfg['SMTP_PORT'])) as server:
            server.starttls()
            server.login(cfg['SMTP_USER'], cfg['SMTP_PASS'])
            server.send_message(msg)
        log.info(f'Alert inviato: {subject}')
        return True
    except Exception as e:
        log.error(f'Errore invio alert: {e}')
        return False


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('Usage: alert.py <subject> <body> [level]')
        sys.exit(1)
    subject = sys.argv[1]
    body = sys.argv[2]
    level = sys.argv[3] if len(sys.argv) > 3 else 'INFO'
    if send_alert(subject, body, level):
        print('OK')
    else:
        print('FAIL')
        sys.exit(1)
