#!/usr/bin/env python3
"""GUARDiA 이메일 발송 스크립트 — 서버에서 직접 실행"""
import paramiko, time, sys

HOST = '101.79.17.164'; USER = 'root'; PASS = '1q2w3e!Q'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(HOST, username=USER, password=PASS, timeout=15)
sftp = client.open_sftp()

# 서버에서 실행할 Python 스크립트를 파일로 저장
mail_script = r"""
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime

TO   = 'ythong86@gmail.com'
FROM = 'guardia@zioinfo.co.kr'
NOW  = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

text_body = """안녕하세요,

GUARDiA ITSM 이메일 발송 테스트입니다.

발신 서버: mail.zioinfo.co.kr (101.79.17.164)
발신자: guardia@zioinfo.co.kr
발송 시각: """ + NOW + """ KST
인증: SPF PASS + DKIM 서명

이 메일이 수신되면 GUARDiA SMTP 서버가 정상 작동하는 것입니다.

(주)지오정보기술 | GUARDiA ITSM v2.0
http://101.79.17.164:8001
"""

html_body = """<!DOCTYPE html>
<html lang="ko">
<head><meta charset="UTF-8"></head>
<body style="font-family:-apple-system,sans-serif;background:#f0f2f5;padding:30px 20px;margin:0">
<div style="max-width:560px;margin:0 auto;background:#fff;border-radius:12px;box-shadow:0 4px 20px rgba(0,0,0,.1);overflow:hidden">
  <div style="background:#1a3a6b;padding:24px 32px;display:flex;align-items:center;gap:14px">
    <span style="font-size:36px">&#128737;</span>
    <div>
      <h1 style="color:#fff;margin:0;font-size:20px;font-weight:800">GUARDiA ITSM</h1>
      <p style="color:#aac4e8;margin:0;font-size:12px">(주)지오정보기술 AI 인프라 자율 운영 플랫폼</p>
    </div>
  </div>
  <div style="padding:28px 32px">
    <h2 style="color:#1a3a6b;margin:0 0 6px;font-size:18px">&#128231; 이메일 발송 테스트</h2>
    <p style="color:#64748b;font-size:13px;margin:0 0 20px">zio 서버 SMTP 서버 정상 동작 확인</p>
    <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:14px 18px;margin-bottom:20px">
      <p style="color:#166534;font-weight:700;margin:0 0 3px;font-size:14px">&#9989; 발송 성공</p>
      <p style="color:#475569;font-size:12px;margin:0">SPF · DKIM 인증을 통과하여 정상 발송되었습니다.</p>
    </div>
    <table style="width:100%;border-collapse:collapse;font-size:13px">
      <tr style="background:#f8fafc">
        <td style="padding:9px 14px;font-weight:600;color:#64748b;border:1px solid #e2e8f0;width:32%">발신 서버</td>
        <td style="padding:9px 14px;color:#1e293b;border:1px solid #e2e8f0">mail.zioinfo.co.kr (101.79.17.164)</td>
      </tr>
      <tr>
        <td style="padding:9px 14px;font-weight:600;color:#64748b;border:1px solid #e2e8f0">발신자</td>
        <td style="padding:9px 14px;color:#1e293b;border:1px solid #e2e8f0">guardia@zioinfo.co.kr</td>
      </tr>
      <tr style="background:#f8fafc">
        <td style="padding:9px 14px;font-weight:600;color:#64748b;border:1px solid #e2e8f0">발송 시각</td>
        <td style="padding:9px 14px;color:#1e293b;border:1px solid #e2e8f0">""" + NOW + """ KST</td>
      </tr>
      <tr>
        <td style="padding:9px 14px;font-weight:600;color:#64748b;border:1px solid #e2e8f0">SPF 인증</td>
        <td style="padding:9px 14px;border:1px solid #e2e8f0">
          <span style="background:#dcfce7;color:#16a34a;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:600">&#9989; PASS</span>
        </td>
      </tr>
      <tr style="background:#f8fafc">
        <td style="padding:9px 14px;font-weight:600;color:#64748b;border:1px solid #e2e8f0">DKIM 서명</td>
        <td style="padding:9px 14px;border:1px solid #e2e8f0">
          <span style="background:#dcfce7;color:#16a34a;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:600">&#9989; 서명됨</span>
        </td>
      </tr>
    </table>
    <div style="margin-top:22px;padding:14px 18px;background:#eff2ff;border-radius:8px;border:1px solid #c7d2fe">
      <p style="color:#1a3a6b;font-weight:700;margin:0 0 8px;font-size:13px">&#129302; GUARDiA ITSM 이메일 알림 기능</p>
      <ul style="color:#475569;font-size:12px;margin:0;padding-left:18px;line-height:2">
        <li>SR 접수/완료 알림</li>
        <li>인시던트 긴급 알림</li>
        <li>SLA 위반 경고</li>
        <li>배포 완료/실패 알림</li>
        <li>라이선스 만료 알림</li>
      </ul>
    </div>
  </div>
  <div style="background:#f8fafc;padding:14px 32px;border-top:1px solid #e2e8f0;text-align:center;font-size:11px;color:#94a3b8">
    GUARDiA ITSM v2.0 자동 발송 | (주)지오정보기술<br>
    guardia@zioinfo.co.kr | http://101.79.17.164:8001
  </div>
</div>
</body></html>
"""

msg = MIMEMultipart('alternative')
msg['Subject'] = '[GUARDiA] SMTP 이메일 발송 테스트 - ' + NOW
msg['From']    = 'GUARDiA ITSM <' + FROM + '>'
msg['To']      = TO
msg['X-Mailer'] = 'GUARDiA ITSM v2.0'
msg.attach(MIMEText(text_body, 'plain', 'utf-8'))
msg.attach(MIMEText(html_body, 'html',  'utf-8'))

try:
    with smtplib.SMTP('localhost', 25, timeout=15) as smtp:
        smtp.ehlo('mail.zioinfo.co.kr')
        refused = smtp.sendmail(FROM, [TO], msg.as_string())
        if refused:
            print('FAIL 거부:', refused)
        else:
            print('OK 발송 완료! ythong86@gmail.com 수신함을 확인하세요.')
            print('발신: ' + FROM)
            print('발송 시각: ' + NOW)
except Exception as ex:
    print('FAIL:', ex)
"""

with sftp.open('/tmp/guardia_mail.py', 'w') as f:
    f.write(mail_script)
sftp.close()

chan = client.get_transport().open_session()
chan.set_combine_stderr(True)
chan.exec_command('python3 /tmp/guardia_mail.py 2>&1')
start = time.time()
while not chan.exit_status_ready():
    if chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096)); sys.stdout.flush()
    if time.time() - start > 20: break
    time.sleep(0.3)
while chan.recv_ready(): sys.stdout.buffer.write(chan.recv(4096))
sys.stdout.flush()
chan.recv_exit_status()
client.close()
