import re, json, urllib.parse, urllib.request, http.cookiejar
BASE='http://127.0.0.1:18084'
jar=http.cookiejar.CookieJar()
opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar), urllib.request.HTTPRedirectHandler())
login=urllib.parse.urlencode({'log':'admin','pwd':'admin-pass-1234','wp-submit':'Log In','redirect_to':BASE+'/wp-admin/','testcookie':'1'}).encode()
req=urllib.request.Request(BASE+'/wp-login.php', data=login, headers={'Content-Type':'application/x-www-form-urlencoded','User-Agent':'UPDiag/1.0'})
with opener.open(req, timeout=30) as r:
    print('login',r.status,r.geturl())
edit_url=BASE+'/wp-admin/post.php?post=4&action=edit'
with opener.open(urllib.request.Request(edit_url,headers={'User-Agent':'UPDiag/1.0'}),timeout=30) as r:
    html=r.read().decode('utf-8','replace')
    print('editor',r.status,r.geturl(),'bytes',len(html))
patterns=[
    r'createNonceMiddleware\(\s*["\']([^"\']+)["\']\s*\)',
    r'"nonce"\s*:\s*"([a-zA-Z0-9]+)"',
    r'_wpnonce["\']?\s*[:=]\s*["\']([a-zA-Z0-9]+)["\']'
]
nonce=None
for p in patterns:
    m=re.search(p,html)
    if m:
        nonce=m.group(1); print('nonce pattern',p,'=>',nonce); break
if not nonce:
    for line in html.splitlines():
        if 'apiFetch' in line or 'nonce' in line.lower():
            print('nonce-ish',line[:600])
    raise SystemExit('REST nonce not found')

def get(path, params):
    url=BASE+path+'?'+urllib.parse.urlencode(params, doseq=True)
    req=urllib.request.Request(url, headers={'X-WP-Nonce':nonce,'Referer':edit_url,'User-Agent':'UPDiag/1.0','Accept':'application/json'})
    try:
        with opener.open(req,timeout=30) as r:
            body=r.read(); print('\nGET',url,'status',r.status,'ct',r.headers.get('Content-Type'),'bytes',len(body)); print(body[:1500].decode('utf-8','replace'))
            try: print('json keys',list(json.loads(body).keys()) if isinstance(json.loads(body),dict) else type(json.loads(body)).__name__)
            except Exception as e: print('JSON ERROR',repr(e))
    except urllib.error.HTTPError as e:
        body=e.read(); print('\nHTTPERR',url,e.code,e.headers.get('Content-Type'),body[:2000].decode('utf-8','replace'))

get('/wp-json/wp/v2/block-renderer/united-pets/source-section', [('context','edit'),('attributes[section]','home-slider')])
get('/wp-json/wp/v2/block-renderer/united-pets/source-section', [('context','edit'),('attributes[section]','home-intro-home')])
get('/wp-json/wp/v2/block-renderer/united-pets/query-cards', [('context','edit'),('attributes[postType]','up_service'),('attributes[title]','Our Services'),('attributes[count]','6')])
