#!/usr/bin/env python3
"""
Restores operator.write + operator.read scopes to OpenClaw device-auth files.
Run after every gateway start to work around OC stripping scopes on restart.
"""
import json, glob, sys, os, time

# Wait for gateway to fully initialize and write its files
# (Gateway writes device-auth.json during startup, overwriting scopes)
time.sleep(10)

BASE = os.path.expanduser('~/.openclaw')
SCOPES = ['operator.write', 'operator.read']

def fix(path):
    try:
        with open(path) as f:
            d = json.load(f)
        if isinstance(d, list):
            changed = False
            for item in d:
                if isinstance(item, dict) and item.get('scopes') != SCOPES:
                    item['scopes'] = SCOPES
                    changed = True
            if changed:
                with open(path, 'w') as f:
                    json.dump(d, f, indent=2)
                print(f'Fixed (list): {path}')
        elif isinstance(d, dict):
            if d.get('scopes') != SCOPES:
                d['scopes'] = SCOPES
                with open(path, 'w') as f:
                    json.dump(d, f, indent=2)
                print(f'Fixed: {path}')
            else:
                print(f'OK: {path}')
    except Exception as e:
        print(f'Skip {path}: {e}')

fix(f'{BASE}/identity/device-auth.json')
for p in glob.glob(f'{BASE}/devices/*.json'):
    fix(p)

print('Scope restoration complete.')
