#!/usr/bin/env python3

from __future__ import annotations

import os
import sys

import django


def _env(name: str, default: str = "") -> str:
    value = os.getenv(name, default)
    return value.strip() if isinstance(value, str) else ""


def _setup_django() -> None:
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.main")
    django.setup()


def _set_default_gym(user) -> None:
    try:
        from wger.gym.models import GymConfig
    except Exception:
        return

    try:
        config = GymConfig.objects.first()
    except Exception:
        return

    if not config or not getattr(config, "default_gym", None):
        return

    profile = getattr(user, "userprofile", None)
    if not profile or getattr(profile, "gym", None):
        return

    profile.gym = config.default_gym
    profile.save()


def _ensure_profile(user) -> None:
    profile = getattr(user, "userprofile", None)
    if not profile:
        return
    if hasattr(profile, "email_verified") and not profile.email_verified:
        profile.email_verified = True
    if hasattr(profile, "is_temporary") and profile.is_temporary:
        profile.is_temporary = False
    profile.save()


def _ensure_admin(username: str, password: str, email: str) -> None:
    from django.contrib.auth.models import User

    if not username or not password:
        raise RuntimeError("admin username/password missing")

    user, created = User.objects.get_or_create(username=username)
    if created:
        user.is_active = True
    if not user.is_staff:
        user.is_staff = True
    if email:
        user.email = email
    user.set_password(password)
    user.save()

    _ensure_profile(user)
    _set_default_gym(user)
    print(f"ensured admin user {username}")


def _ensure_user(username: str, password: str, email: str) -> None:
    from django.contrib.auth.models import User

    if not username or not password:
        raise RuntimeError("username/password missing")

    user, created = User.objects.get_or_create(username=username)
    if created:
        user.is_active = True
    if email and user.email != email:
        user.email = email
    user.set_password(password)
    user.save()

    _ensure_profile(user)
    _set_default_gym(user)
    action = "created" if created else "updated"
    print(f"{action} user {username}")


def main() -> int:
    admin_user = _env("WGER_ADMIN_USERNAME")
    admin_password = _env("WGER_ADMIN_PASSWORD")
    admin_email = _env("WGER_ADMIN_EMAIL")

    username = _env("WGER_USERNAME") or _env("ONLY_USERNAME")
    password = _env("WGER_PASSWORD")
    email = _env("WGER_EMAIL")

    if not any([admin_user and admin_password, username and password]):
        print("no admin or user payload provided; exiting")
        return 0

    _setup_django()

    if admin_user and admin_password:
        _ensure_admin(admin_user, admin_password, admin_email)

    if username and password:
        _ensure_user(username, password, email)

    return 0


if __name__ == "__main__":
    sys.exit(main())
