#!/usr/bin/env python3
"""Find Authentik API paths and create Homarr OAuth2 provider."""
import urllib.request, json, sys, re

AK = "9LyRvCaRLSmDrkGxQ45xRKt0JrBWMe3tI3sV2x0HV30mMcxaDBEA4cJ8QDZ2"
BASE = "http://localhost:9000"

def api(method, path, data=None):
    req = urllib.request.Request(f"{BASE}{path}",
        data=json.dumps(data).encode() if data else None,
        headers={"Authorization": f"Bearer {AK}", "Content-Type": "application/json"},
        method=method)
    try:
        with urllib.request.urlopen(req) as r:
            return json.loads(r.read())
    except urllib.error.HTTPError as e:
        body = e.read().decode()[:300]
        print(f"  {method} {path}: {e.code} {body}")
        return None

# Get API browser HTML to find paths
req = urllib.request.Request(f"{BASE}/api/v3/",
    headers={"Authorization": f"Bearer {AK}"})
with urllib.request.urlopen(req) as r:
    html = r.read().decode()

# Find all API paths from the browser
paths = set(re.findall(r'href="([^"]+)"', html))
api_paths = [p for p in paths if '/api/v3/' in p]
print("API paths found:")
for p in sorted(api_paths):
    print(f"  {p}")
