"""اعمال تم فارسی torbatyar و locale پیش‌فرض fa روی realm superapp."""
from __future__ import annotations

import os
import sys

import httpx

KEYCLOAK_URL = os.getenv("KEYCLOAK_SERVER_URL", "http://localhost:8080")
REALM = os.getenv("KEYCLOAK_REALM", "superapp")
ADMIN_USER = os.getenv("KEYCLOAK_ADMIN", "admin")
ADMIN_PASS = os.getenv("KEYCLOAK_ADMIN_PASSWORD", "admin")


def main() -> int:
    with httpx.Client(timeout=15.0) as client:
        token_resp = client.post(
            f"{KEYCLOAK_URL}/realms/master/protocol/openid-connect/token",
            data={
                "grant_type": "password",
                "client_id": "admin-cli",
                "username": ADMIN_USER,
                "password": ADMIN_PASS,
            },
        )
        token_resp.raise_for_status()
        headers = {"Authorization": f"Bearer {token_resp.json()['access_token']}"}

        realm_resp = client.get(f"{KEYCLOAK_URL}/admin/realms/{REALM}", headers=headers)
        realm_resp.raise_for_status()
        data = realm_resp.json()

        data["displayName"] = "Torbatyar"
        data["displayNameHtml"] = "<div>Torbatyar</div>"
        data["internationalizationEnabled"] = True
        data["supportedLocales"] = ["fa", "en"]
        data["defaultLocale"] = "fa"
        data["loginTheme"] = "torbatyar"
        data["accountTheme"] = "torbatyar"
        data["emailTheme"] = "torbatyar"

        update_resp = client.put(
            f"{KEYCLOAK_URL}/admin/realms/{REALM}",
            headers=headers,
            json=data,
        )
        update_resp.raise_for_status()
        print(f"Realm '{REALM}' updated: theme=torbatyar, locale=fa")
        return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as exc:
        print(f"Error: {exc}", file=sys.stderr)
        raise SystemExit(1) from exc
