"""
SSH Email Relay
================
Sends emails through VPS via SSH since local SMTP ports are blocked.
Uses VPS localhost port 25 (Postfix) — no auth needed for local connections.

Usage:
    from scripts.ssh_send_email import send_email_via_ssh
    result = send_email_via_ssh("to@example.com", "Subject", "<html>...</html>")

    # Or as CLI:
    python scripts/ssh_send_email.py recipient@example.com
"""
import base64
import json
import os
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

_PROJECT_ROOT = Path(__file__).resolve().parent.parent
_NO_WIN = 0x08000000 if sys.platform == "win32" else 0
_SSH_KEY = os.path.expanduser("~/.ssh/biznode_deploy")
_SSH_OPTS = [
    "-i", _SSH_KEY, "-p", "28",
    "-o", "ConnectTimeout=10",
    "-o", "StrictHostKeyChecking=no",
]

# Remote script: reads payload from stdin, sends via localhost:25 Postfix
_REMOTE_SCRIPT = """import base64,json,smtplib,sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
d=json.loads(base64.b64decode(sys.stdin.read().strip()).decode())
m=MIMEMultipart("alternative")
m["From"]=d.get("from_addr","biznode@1bz.biz")
m["To"]=d["to"]
m["Subject"]=d["subject"]
m.attach(MIMEText(d["html"],"html"))
s=smtplib.SMTP("localhost",25)
s.sendmail(m["From"],[d["to"]],m.as_string())
s.quit()
print("EMAIL_SENT_OK")
"""


def send_email_via_ssh(to_email, subject, html_body, from_addr="biznode@1bz.biz"):
    """Send an HTML email by SSHing into VPS and using its local Postfix."""
    payload = base64.b64encode(json.dumps({
        "to": to_email,
        "subject": subject,
        "html": html_body,
        "from_addr": from_addr,
    }).encode()).decode()

    ssh_base = ["ssh"] + _SSH_OPTS + ["root@1bz.biz"]

    try:
        # Step 1: Write script to VPS
        r1 = subprocess.run(
            ssh_base + ["cat > /tmp/bzsend.py"],
            input=_REMOTE_SCRIPT,
            capture_output=True, text=True, timeout=15,
            creationflags=_NO_WIN,
        )
        if r1.returncode != 0:
            return {"success": False, "error": f"Failed to upload script: {r1.stderr.strip()}"}

        # Step 2: Pipe payload via stdin to the script
        r2 = subprocess.run(
            ssh_base + ["python3 /tmp/bzsend.py"],
            input=payload,
            capture_output=True, text=True, timeout=30,
            creationflags=_NO_WIN,
        )
        if "EMAIL_SENT_OK" in r2.stdout:
            return {"success": True, "message": f"Email sent to {to_email}"}
        return {"success": False, "error": r2.stderr.strip()[:300] or r2.stdout.strip() or "Unknown error"}
    except subprocess.TimeoutExpired:
        return {"success": False, "error": "SSH connection timed out"}
    except Exception as exc:
        return {"success": False, "error": str(exc)}


if __name__ == "__main__":
    to = sys.argv[1] if len(sys.argv) > 1 else "shashi@1bz.biz"
    date_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    subj = f"BizNode \u2014 Personalized for you ({date_str}) [TEST]"

    html = (
        '<!DOCTYPE html><html><body style="background:#0A0D14;padding:20px;font-family:Arial;">'
        '<div style="max-width:550px;margin:0 auto;background:#111827;border-radius:12px;overflow:hidden;">'
        '<div style="background:linear-gradient(135deg,#4F46E5,#7C3AED);padding:20px 24px;">'
        '<img src="https://biznode.1bz.biz/logos/biznodelogo.png" width="40" height="40" style="border-radius:8px;vertical-align:middle;"> '
        '<span style="font-size:16px;font-weight:700;color:#fff;vertical-align:middle;">BizNode</span>'
        '<h1 style="margin:10px 0 0;font-size:18px;color:#fff;">Hi Shashi, here is what is new</h1></div>'
        '<div style="padding:24px;color:#E2E8F0;">'
        '<h3 style="color:#A78BFA;">Your Interests</h3>'
        '<ul style="list-style:none;padding:0;">'
        '<li style="color:#D1D5DB;">&#8226; tool marketplace - 5x</li>'
        '<li style="color:#D1D5DB;">&#8226; pricing - 3x</li>'
        '<li style="color:#D1D5DB;">&#8226; hosted agents - 2x</li></ul>'
        '<div style="background:#1F2937;border-radius:8px;padding:16px;margin:16px 0;">'
        '<p style="color:#F59E0B;font-weight:600;">Pick up where you left off</p>'
        '<p style="color:#D1D5DB;">Last: <em>How does escrow work?</em></p></div>'
        '<div style="background:rgba(99,102,241,.08);border-radius:8px;padding:16px;margin:16px 0;">'
        '<h3 style="color:#22d3ee;">Latest from BizNode + 1BZ</h3>'
        '<p style="color:#D1D5DB;font-size:13px;">7-tier marketplace from $20 | Tool publishing earns DZIT | CopyGuard IP protection</p></div>'
        '<div style="padding:12px;background:#1F2937;border-radius:8px;">'
        '<p style="color:#9CA3AF;font-size:12px;margin:0 0 8px;">Explore 1BZ ecosystem:</p>'
        '<a href="https://1bz.biz" style="color:#818cf8;font-size:12px;">1BZ</a> | '
        '<a href="https://dzit.1bz.biz" style="color:#22d3ee;font-size:12px;">DZIT</a> | '
        '<a href="https://biznode.1bz.biz" style="color:#A78BFA;font-size:12px;">BizNode</a> | '
        '<a href="https://copyguard.1bz.biz" style="color:#22c55e;font-size:12px;">CopyGuard</a> | '
        '<a href="https://ipvault.1bz.biz" style="color:#f59e0b;font-size:12px;">IPVault</a> | '
        '<a href="https://smartpdf.1bz.biz" style="color:#ef4444;font-size:12px;">SmartPDF</a></div>'
        '</div>'
        '<div style="padding:12px;text-align:center;font-size:11px;color:#6B7280;border-top:1px solid #1F2937;">'
        'BizNode &mdash; <a href="https://1bz.biz" style="color:#60A5FA;">1BZ ecosystem</a></div>'
        '</div></body></html>'
    )

    result = send_email_via_ssh(to, subj, html)
    print(json.dumps(result, indent=2))
