"""Probe Dataforth API: get token, fetch Swagger, list relevant endpoints."""
import json, os, subprocess, urllib.request
import yaml

creds = yaml.safe_load(subprocess.run(['sops','-d','D:/vault/clients/dataforth/api-oauth.sops.yaml'],
    capture_output=True, text=True, timeout=30, check=True).stdout)
TOKEN_URL = creds['endpoints']['token-url']
SWAGGER_JSON = creds['endpoints']['swagger-json']
API_BASE = creds['endpoints']['api-base']
C = creds['credentials']

# 1. Get token
print('[1] fetch OAuth token')
body = (f'grant_type={C["grant-type"]}&client_id={C["client-id"]}'
        f'&client_secret={C["client-secret"]}&scope={C["scope"]}').encode()
req = urllib.request.Request(TOKEN_URL, data=body, method='POST',
    headers={'Content-Type':'application/x-www-form-urlencoded'})
with urllib.request.urlopen(req, timeout=30) as r:
    tok = json.loads(r.read())
print(f'  access_token: {tok["access_token"][:30]}... (expires_in={tok.get("expires_in")}s)')
ACCESS = tok['access_token']

# 2. Pull swagger
print('\n[2] fetch swagger')
req = urllib.request.Request(SWAGGER_JSON,
    headers={'Authorization': f'Bearer {ACCESS}'})
with urllib.request.urlopen(req, timeout=30) as r:
    sw = json.loads(r.read())
print(f'  title: {sw.get("info",{}).get("title")}, version: {sw.get("info",{}).get("version")}')
print(f'  total paths: {len(sw.get("paths",{}))}')

# 3. Filter paths for upload/datasheet/file/test
print('\n[3] paths matching upload/datasheet/file/test/report:')
hits = []
for path, methods in sw.get('paths',{}).items():
    pl = path.lower()
    if any(k in pl for k in ('upload','datasheet','testreport','file','data')):
        for m, op in methods.items():
            if m.startswith('x-'): continue
            hits.append((m.upper(), path, op.get('summary','') or op.get('operationId','')))
for m,p,desc in sorted(hits)[:40]:
    print(f'  {m:6} {p:60} {desc[:60]}')

# 4. Save full swagger for offline reading
out = r'D:\claudetools\projects\dataforth-dos\dfwds-research\swagger.json'
with open(out,'w',encoding='utf-8') as f: json.dump(sw, f, indent=2)
print(f'\nfull swagger saved: {out}')
