import os
from typing import Optional

from dotenv import load_dotenv
from ldap3 import ALL, Connection, Server

load_dotenv()


def ldap_authenticate(username: str, password: str) -> Optional[dict]:
    ldap_url = os.environ.get("LDAP_URL")
    ldap_user_dn = os.environ.get("LDAP_USER_DN")
    ldap_base = os.environ.get("LDAP_BASE_DN")
    if not ldap_url:
        # Fallback mock for local development: accept any user with password 'password'
        if password == "password":
            return {"username": username, "groups": ["local"]}
        return None

    try:
        server = Server(ldap_url, get_info=ALL)
        conn = Connection(server, user=username, password=password, auto_bind=True)
        # Simple success -> return username; group resolution left for future
        return {"username": username, "groups": []}
    except Exception:
        return None
