#!/usr/bin/env python3
"""Galaktikus-Wachhund: Mini-App + beide Domains + APIs.
Auto-Heilung: leere mini_app.html -> Restore vom besten Backup. Owner-Alert via Telegram."""
import urllib.request, ssl, json, os, glob, shutil, subprocess, sys

CTX = ssl.create_default_context(); CTX.check_hostname = False; CTX.verify_mode = ssl.CERT_NONE
TG = json.load(open('/home/marcel7364/.secrets/telegram_notify.json'))
BOT, CHAT = TG['token'], TG['chat_id']

def http(url, timeout=25, data=None):
    hdrs = {'User-Agent': 'GK-Watchdog/1.0'}
    if data is not None:
        hdrs['Content-Type'] = 'application/json'
    req = urllib.request.Request(url, data=data, headers=hdrs)
    with urllib.request.urlopen(req, timeout=timeout, context=CTX) as r:
        return r.status, r.read()

def notify(msg):
    try:
        body = json.dumps({'chat_id': CHAT, 'text': msg[:4000]}).encode()
        http(f'https://api.telegram.org/bot{BOT}/sendMessage', data=body)

    except Exception:
        pass

def js_valid(html):
    try:
        import re
        blocks = re.findall(r'<script[^>]*>(.*?)</script>', html, re.S)
        for i, s in enumerate(blocks):
            # QFIX 261126: eindeutige Temp-Datei statt fester Namen (/tmp/wd_js_N.js
            # wurde von fremden Nutzern angelegt -> PermissionError -> Falsch-FAIL)
            import tempfile
            fh = tempfile.NamedTemporaryFile('w', suffix=f'.wd{i}.js', delete=False, encoding='utf-8')
            fh.write(s); fh.close(); p = fh.name
            try:
                if subprocess.run(['/home/marcel7364/.hermes/tools/node-26.12.1-linux-x64/bin/node', '--check', p], capture_output=True).returncode != 0:
                    return False
            finally:
                try: os.unlink(p)
                except Exception: pass
        return True
    except Exception:
        return False

CHECKS = []  # (name, ok, detail)
def check(name, ok, detail=''):
    CHECKS.append((name, ok, detail))
    return ok

# --- 1) Mini-App /app: Groesse + JS
try:
    st, body = http('https://galaktikus.org/app?v=wd')
    ok = st == 200 and len(body) > 1000 and js_valid(body.decode('utf-8', 'ignore'))
    check('Mini-App /app', ok, f'{st}, {len(body)} B')
except Exception as e:
    check('Mini-App /app', False, str(e)[:80])

# --- Auto-Heilung Mini-App
if not CHECKS[-1][1]:
    baks = sorted(glob.glob('/opt/galaktikus-ai/backups/mini_app_*.html'), key=os.path.getmtime, reverse=True)
    good = None
    for b in baks:
        try:
            sz = os.path.getsize(b)
            if sz > 1000 and js_valid(open(b, encoding='utf-8', errors='ignore').read()):
                good = b; break
        except Exception:
            continue
    if good:
        subprocess.run(['sudo', 'cp', good, '/opt/galaktikus-ai/mini_app.html'], check=True)
        subprocess.run(['sudo', 'chown', 'www-data:www-data', '/opt/galaktikus-ai/mini_app.html'], check=True)
        st2, body2 = http('https://galaktikus.org/app?v=wd2')
        healed = st2 == 200 and len(body2) > 1000
        check('AUTO-HEILUNG', healed, f'restored {os.path.basename(good)}')
        notify('🚨 Wachhund: Mini-App war KAPUTT — auto-restauriert aus ' + os.path.basename(good) + (', LIVE wieder OK' if healed else ', IMMER NOCH KAPUTT — mannuell pruefen!'))
    else:
        notify('🚨 Wachhund: Mini-App kaputt und KEIN gueltiges Backup gefunden!')
        check('AUTO-HEILUNG', False, 'kein Backup')

# --- 2) Backend-APIs (org)
try:
    st, b = http('https://galaktikus.org/healthz'); check('org healthz', st == 200, str(st))
except Exception as e:
    check('org healthz', False, str(e)[:60])
try:
    body = json.dumps({'guest_id': 'wd-' + os.urandom(8).hex(), 'message': 'ping'}).encode()
    st, b = http('https://galaktikus.org/api/guest', data=body)
    # 429 = Ratenlimit/Paywall aktiv = API lebt -> OK
    ok = (st == 200 and b'"reply"' in b) or st == 429
    check('Gast-Chat-API', ok, f'{st}')
except Exception as e:
    check('Gast-Chat-API', False, str(e)[:60])

# --- 3) Domains + Logo
for name, url in [('galaktikus.org', 'https://galaktikus.org/'), ('galaktikus.ai', 'https://galaktikus.ai/'),
                  ('Logo', 'https://galaktikus.org/logo.png'), ('GKAI-Seite', 'https://galaktikus.org/gkai.html')]:
    try:
        st, b = http(url); check(name, st == 200, f'{st}, {len(b)} B')
    except Exception as e:
        check(name, False, str(e)[:60])

# --- 4) Services
svc = subprocess.run(['systemctl', 'is-active', 'galaktikus-ai'], capture_output=True, text=True).stdout.strip()
check('Service galaktikus-ai', svc == 'active', svc)

fails = [c for c in CHECKS if not c[1]]
line = lambda: ' | '.join(f"{'OK' if ok else 'FAIL:' + d} {n}" for n, ok, d in CHECKS)
if fails:
    notify('🚨 Galaktikus-Wachhund ALARM:\n' + '\n'.join(f'❌ {n} — {d}' for n, ok, d in fails))
print(line())
sys.exit(1 if fails else 0)
