#!/usr/bin/env python3
# EQVPS-Dauerhaftigkeits-Wächter (21.11., Patron-Befehl "dauerhaft")
# Cron tgl. 09:20 UTC. Stille Wache: verlängert automatisch von Guthaben,
# solange Decke reicht; alarmiert Patron via @Galaktikus_ai_bot NUR bei Handlungsbedarf.
import json, urllib.request, datetime, os, sys

SEC = '/home/marcel7364/.secrets/eqvps.json'
TGB = '/home/marcel7364/.secrets/galaktikus_ai_bot.json'
LOG = '/home/marcel7364/.hermes/profiles/galaktikus/logs/eqvps_renew_guard.log'
MARKER = '/home/marcel7364/.hermes/profiles/galaktikus/logs/eqvps_alert_marker'
PATRON_TG = '6231972678'
SVC = ['2MGEGTH', '5KC2K6C']          # DEV-BOX ARTEX, GK-BACKUP-1
MIN_BALANCE_ALERT = 60                 # USD: darunter -> Patron-Alarm
RENEW_THRESHOLD_DAYS = 25              # Ablauf <=X Tage -> auto-renew

def log(msg):
    os.makedirs(os.path.dirname(LOG), exist_ok=True)
    with open(LOG, 'a') as f:
        f.write(f"{datetime.datetime.now(datetime.timezone.utc).isoformat()} {msg}\n")

def api(path, body=None, method='GET'):
    tok = json.load(open(SEC))['api_token']
    url = f'https://api.eqvps.com/api/v1/eqvps{path}'
    req = urllib.request.Request(url, data=(json.dumps(body).encode() if body else None), method=method,
        headers={'Authorization': f'Bearer {tok}', 'User-Agent': 'Mozilla/5.0',
                 'Accept': 'application/json', 'Content-Type': 'application/json'})
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            return r.status, json.loads(r.read())
    except Exception as e:
        return getattr(e, 'code', -1), {'error': str(e)[:150]}

def alert(text):
    today = datetime.date.today().isoformat()
    last = ''
    if os.path.exists(MARKER):
        last = open(MARKER).read().strip()
    if last == today:   # max 1 Alarm/Tag
        return
    tok = json.load(open(TGB))['token']
    req = urllib.request.Request(
        f'https://api.telegram.org/bot{tok}/sendMessage',
        data=json.dumps({'chat_id': PATRON_TG, 'text': text}).encode(),
        headers={'Content-Type': 'application/json'})
    urllib.request.urlopen(req, timeout=30)
    with open(MARKER, 'w') as f:
        f.write(today)
    log('ALERT gesendet: ' + text[:80])

def main():
    st, bal = api('/balance')
    if st != 200 or 'real_balance' not in bal:
        log('FEHLER Balance-Check: ' + str(bal)[:120]); return
    balance = float(bal['real_balance'])
    for sid in SVC:
        st, svc = api(f'/services/{sid}')
        if st != 200 or 'data' not in svc:
            log(f'FEHLER Service-Check {sid}'); continue
        exp = datetime.datetime.fromisoformat(svc['data']['expires_at'].replace('Z', '+00:00'))
        days_left = (exp - datetime.datetime.now(datetime.timezone.utc)).days
        if days_left <= RENEW_THRESHOLD_DAYS and balance >= 45:
            st, res = api(f'/services/{sid}/renew', {'months': 1}, 'POST')
            if st == 200 and res.get('paid_from_balance'):
                balance -= 20
                log(f'AUTO-RENEW {sid}: bis {res.get("new_expires_at")} (-20$)')
            else:
                alert(f'⚠️ EQVPS Auto-Renew {sid} fehlgeschlagen ({st}) — bitte prüfen!')
                log(f'RENEW-FAIL {sid}: ' + str(res)[:150])
        elif days_left > RENEW_THRESHOLD_DAYS:
            log(f'{sid} OK: {days_left} Tage Rest')
    st, bal = api('/balance')
    if st == 200 and float(bal['real_balance']) < MIN_BALANCE_ALERT:
        alert(f'💰 EQVPS-Guthaben niedrig: {bal["real_balance"]}$ — für Dauerlauf der Boxen (ARTEX+Backup) aufladen!')

if __name__ == '__main__':
    main()
