#!/usr/bin/env python3
# NowPayments-Aktivierungs-Wache: prueft gkai-mail auf NowPayments-Mails,
# aktiviert den Account per Link-Aufruf und benachrichtigt den Owner via Telegram.
import sqlite3, re, subprocess, sys, os, json, urllib.request

MAILDB = '/var/www/gkai-mail/data/mail.sqlite'
STATE = '/home/marcel7364/.hermes/profiles/galaktikus/cache/scratch/np_wache_state.json'
BOT = json.load(open('/home/marcel7364/.secrets/galaktikus_ai_bot.json'))
if isinstance(BOT, dict):
    BOT = BOT.get('token') or BOT.get('bot_token') or list(BOT.values())[0]
OWNER = 6231972678

def send(text):
    data = json.dumps({'chat_id': OWNER, 'text': text}).encode()
    req = urllib.request.Request(f'https://api.telegram.org/bot{BOT}/sendMessage',
                                 data=data, headers={'Content-Type': 'application/json'})
    try:
        urllib.request.urlopen(req, timeout=30)
    except Exception as e:
        print('TG-Fehler:', e)

state = json.load(open(STATE)) if os.path.exists(STATE) else {'last_id': 70, 'done': False}
if state.get('done'):
    sys.exit(0)  # still: bereits aktiviert

conn = sqlite3.connect(MAILDB)
rows = conn.execute("SELECT id, sender, subject, body_text, body_html FROM mails "
                   "WHERE id > ? AND (recipient LIKE '%brandt%' OR sender LIKE '%nowpayments%') "
                   "ORDER BY id DESC LIMIT 10", (state['last_id'],)).fetchall()
conn.close()
if not rows:
    sys.exit(0)  # still: keine neue Mail = keine Nachricht an den Owner

for r in rows:
    print('Mail:', r[0], '|', r[1], '|', r[2])
    text = (r[3] or '') + ' ' + (r[4] or '')
    links = [l for l in re.findall(r'https?://[^\s<>"\'\) ]+', text) if 'nowpayments' in l]
    if links:
        link = links[0]
        print('Aktivierungs-Link:', link[:120])
        code = subprocess.run(['curl', '-s', '-o', '/dev/null', '-w', '%{http_code}',
                              '-A', 'Mozilla/5.0', link], capture_output=True, text=True).stdout
        state['done'] = True
        state['last_id'] = r[0]
        json.dump(state, open(STATE, 'w'))
        send(f'NowPayments: Aktivierungs-Mail da, Link aufgerufen (HTTP {code}). '
             f'API-Key kann jetzt geholt werden. Link: {link[:150]}')
        print('AKTIVIERUNG DURCHGEFUEHRT, HTTP', code)
        sys.exit(0)
state['last_id'] = rows[0][0]
json.dump(state, open(STATE, 'w'))
print('Mail ohne Link.')
