#!/usr/bin/env python3
"""Forge-Bereitstellungs-Wache: prueft vpsbit galaktikus-forge-1 Status.
Druckt NUR bei ZUSTANDSAENDERUNG (neuer Server / status=active mit IP)."""
import json, os, sys, urllib.request

STATE = os.path.expanduser('~/.hermes/profiles/galaktikus/cache/scratch/forge_wache_state.txt')
LABEL = 'galaktikus-forge-1'

def check():
    tok = json.load(open(os.path.expanduser('~/.secrets/vpsbit_forge_account.json')))['account_token']
    req = urllib.request.Request('https://vpsbit.io/api/login',
        data=json.dumps({'mode': 'token', 'token': tok, 'tos': True}).encode(),
        headers={'Content-Type': 'application/json', 'Origin': 'https://vpsbit.io',
                 'Referer': 'https://vpsbit.io/panel/'})
    with urllib.request.urlopen(req, timeout=30) as r:
        cookie = r.headers.get('Set-Cookie', '').split(';')[0]
    req = urllib.request.Request('https://vpsbit.io/api/servers',
        headers={'Cookie': cookie, 'Origin': 'https://vpsbit.io',
                 'Referer': 'https://vpsbit.io/panel/'})
    with urllib.request.urlopen(req, timeout=30) as r:
        servers = json.loads(r.read()).get('servers', [])
    mine = [s for s in servers if s.get('label') == LABEL]
    return mine or servers

def main():
    try:
        mine = check()
    except Exception as e:
        print(f'FORGE-WACHE FEHLER: {e}')  # Fehler sichtbar machen, cron liefert nur bei Output
        return
    if not mine:
        print('FORGE: Server noch nicht im Account sichtbar (Bestellung 1288 bezahlt, wartet auf Provisioning)')
        return
    s = mine[0]
    sig = f"{s.get('id')}:{s.get('status')}:{s.get('power_state')}"
    old = ''
    try:
        old = open(STATE).read().strip()
    except OSError:
        pass
    if sig != old:
        open(STATE, 'w').write(sig)
        if s.get('status') == 'active':
            print(f"FORGE AKTIV! Server-ID {s.get('id')} — Status: {s.get('status')}. "
                  f"Galaktikus: Jetzt Setup starten (SSH-Key ~/.ssh/gk_forge_ed25519).")
        else:
            print(f"FORGE-Statuswechsel: {s.get('status')} (Server-ID {s.get('id')}) — noch kein GO fuer Setup.")
    # unveraendert: stille Post

if __name__ == '__main__':
    main()
