import argparse
import os
import sys

import django

LOG_PATH = os.environ.get("AUTH_DEBUG_LOG", "/tmp/auth_debug.log")


def log(data):
    try:
        with open(LOG_PATH, "a") as f:
            f.write(f"{data}\n")
    except Exception:
        pass


# Set up Django environment
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")  # Adjust if needed
django.setup()

from django.contrib.auth import authenticate  # noqa: E402
from django.contrib.auth.models import User  # noqa: E402


def check_credentials(username, password):
    """Authenticate user via Django"""
    user = authenticate(username=username, password=password)
    return user is not None and user.is_active


def _handle_line(line: str) -> str:
    parts = line.split(":")
    if len(parts) < 3:
        return "0"

    command, username, domain = parts[:3]
    _ = domain
    password = ":".join(parts[3:]) if len(parts) > 3 else None

    if command == "auth":
        return "1" if (password and check_credentials(username, password)) else "0"
    if command == "isuser":
        return "1" if User.objects.filter(username=username).exists() else "0"
    if command == "setpass":
        return "0"
    return "0"


def _readline() -> tuple[str | None, bool]:
    raw = sys.stdin.readline()
    if raw == "":
        return None, True
    return raw.rstrip("\r\n"), False


def main(*, once: bool = False):
    """Process authentication requests from Prosody."""
    while True:
        try:
            line, eof = _readline()
            if eof:
                break
            if line is None:
                break
            if line == "":
                if once:
                    print("0", flush=True)
                    return
                continue

            result = _handle_line(line)
            print(result, flush=True)
            if once:
                return
        except Exception as e:
            log(f"Error: {str(e)}")
            print("0", flush=True)
            if once:
                return


if __name__ == "__main__":
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("--once", action="store_true")
    args, _unknown = parser.parse_known_args()
    main(once=bool(args.once))
