#!/usr/bin/env python3
"""Create Authentik OAuth2 provider + application for Homarr."""
import urllib.request, json, sys

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:
        print(f"  {method} {path}: {e.code} {e.read().decode()[:200]}")
        return None

# 1. Get authorization flow
flows = api("GET", "/api/v3/flows/?slug=provider-authorization-implicit-consent")
if not flows or not flows.get("results"):
    # Try alternative
    flows = api("GET", "/api/v3/flows/")
    if flows:
        print(f"Available flows: {[(f['slug'], f['name']) for f in flows.get('results',[])]}")
        flow_pk = flows["results"][0]["pk"]
    else:
        sys.exit(1)
else:
    flow_pk = flows["results"][0]["pk"]
print(f"Flow PK: {flow_pk}")

# 2. Get provider type
provider_types = api("GET", "/api/v3/providers/all/types/")
print(f"Provider types: {provider_types}")

# 3. Create OAuth2 provider
provider = api("POST", "/api/v3/providers/oauth2/", {
    "name": "Homarr",
    "authorization_flow": flow_pk,
    "client_type": "confidential",
    "redirect_uris": "http://localhost:7575/api/auth/callback/authentik"
})
if provider:
    print(f"Provider created: {provider.get('pk')} client_id={provider.get('client_id')}")
    client_id = provider.get("client_id")
    client_secret = provider.get("client_secret")
    
    # 4. Create Application
    app = api("POST", "/api/v3/core/applications/", {
        "name": "Homarr",
        "slug": "homarr",
        "provider": provider["pk"]
    })
    if app:
        print(f"Application created: {app.get('pk')} slug={app.get('slug')}")
        print(f"\nHomarr OIDC config:")
        print(f"  Client ID: {client_id}")
        print(f"  Client Secret: {client_secret}")
        print(f"  Issuer: http://localhost:9000/application/o/homarr/")
    else:
        print("Failed to create application")
