#  Copyright (c) 2022. The Pycroft Authors. See the AUTHORS file.
#  This file is part of the Pycroft project and licensed under the terms of
#  the Apache License, Version 2.0. See the LICENSE file for details
import os
from collections import namedtuple
from distutils.util import strtobool

from ldap_sync import logger

_sync_config = namedtuple(
    'LdapSyncConfig',
    ['host', 'port', 'use_ssl', 'ca_certs_file', 'ca_certs_data', 'bind_dn',
     'bind_pw', 'base_dn', 'db_uri', 'required_property']
)


def _from_environ_or_defaults(key, defaults):
    try:
        return os.environ[f'PYCROFT_LDAP_{key.upper()}']
    except KeyError as e:
        if key not in defaults:
            print("defaults:", defaults)
            raise ValueError(f"Missing configuration key {key}") from e
        return defaults[key]


def get_config(**defaults):
    config_dict = {
        # e.g. 'host': 'PYCROFT_LDAP_HOST'
        key: _from_environ_or_defaults(key, defaults)
        for key in _sync_config._fields if key != 'db_uri'
    }
    config_dict['port'] = int(config_dict['port'])
    if 'use_ssl' in config_dict:
        config_dict['use_ssl'] = bool(strtobool(config_dict['use_ssl']))
    config_dict['db_uri'] = os.environ['PYCROFT_DB_URI']
    config = _sync_config(**config_dict)

    return config


def get_config_or_exit(**defaults):
    try:
        return get_config(**defaults)
    except KeyError as exc:
        logger.critical("%s not set, quitting", exc.args[0])
        exit()

@@ -223,27 +223,22 @@
 rom 
-collections
+typing
  import 
 name
@@ -233,22 +233,22 @@
  import 
-n
+N
 amed
-t
+T
 uple%0Afro
@@ -316,172 +316,252 @@
 er%0A%0A
-_sync_c
+%0Aclass SyncC
 onfig
- = n
+(N
 amed
-t
+T
 uple
-(
+):
 %0A    
-'LdapSyncConfig',%0A    %5B'host', 'port', 'use_ssl', 'ca_certs_file', 'ca_certs_data', '
+# DB-related%0A    db_uri: str%0A    # LDAP-related%0A    host: str%0A    port: int%0A    use_ssl: bool%0A    ca_certs_file: str %7C None%0A    ca_certs_data: str %7C None%0A    
 bind_dn
-',
+: str
 %0A    
- '
 bind_pw
-', 'base_dn', 'db_uri', '
+: str%0A    base_dn: str%0A    
 requ
@@ -577,12 +577,13 @@
 erty
-'%5D%0A)
+: str
 %0A%0A%0Ad
@@ -1059,23 +1059,21 @@
  key in 
-_sync_c
+SyncC
 onfig._f
@@ -1325,24 +1325,20 @@
     
-config = _sync_c
+return SyncC
 onfi
@@ -1359,27 +1359,8 @@
 t)%0A%0A
-    return config%0A%0A
 %0Adef

use typed namedtuple for ldap sync config