#!/usr/bin/env python3
"""
Watches OpenClaw device-auth.json and restores operator scopes when stripped.
Runs as a persistent systemd service. Checks every 10s.
"""
import json, glob, os, time, sys

BASE = os.path.expanduser('~/.openclaw')
DEVICE_AUTH = f'{BASE}/identity/device-auth.json'
SCOPES = ['operator.write', 'operator.read']
CHECK_INTERVAL = 10  # seconds

def needs_fix():
    try:
        with open(DEVICE_AUTH) as f:
            return json.load(f).get('scopes') != SCOPES
    except:
        return False

def restore_scopes():
    fixed = []
    for p in [DEVICE_AUTH] + glob.glob(f'{BASE}/devices/*.json'):
        try:
            with open(p) as f:
                data = json.load(f)
            changed = False
            items = data if isinstance(data, list) else [data]
            for item in items:
                if isinstance(item, dict) and item.get('scopes') != SCOPES:
                    item['scopes'] = SCOPES
                    changed = True
            if changed:
                with open(p, 'w') as f:
                    json.dump(data, f, indent=2)
                fixed.append(os.path.basename(p))
        except:
            pass
    return fixed

print('[scope-watchdog] Starting. Checking every 10s.', flush=True)

while True:
    if needs_fix():
        fixed = restore_scopes()
        if fixed:
            print(f'[scope-watchdog] Restored: {fixed}', flush=True)
    time.sleep(CHECK_INTERVAL)
