'''
this script is used to check if a tenant and user exist in the database and if support is active for that tenant.
and its supposed to be run in TeamCity
'''
from actions_logging.app_logging import logger
from mongo.mongo_apis import MongoClientManager, count_documents
import os



def get_required_env_var(var_name):
    """
    Get the required environment variable. If not found, exit with logger.error and exit(1).
    """
    try:
        value = os.environ[var_name]
        if not value:
            logger.error(f"Environment variable {var_name} is empty: {e}")
            exit(1)
        return value
    except KeyError:
        logger.error(f"Environment variable {var_name} is not set.")
        exit(1)
    except Exception as e:
        logger.error(f"Error retrieving environment variable {var_name}: {e}")
        exit(1)



def main():
    try:
        env_name = get_required_env_var('ENVIRONMENT')
        tenant_name = get_required_env_var('TENANT_HOST').split(".")[0] # the tenant host we are getting is the url we need just the subdomain
        logger.info_green(f"tenant name is {tenant_name}")
        tenant_mail = get_required_env_var('TENANT_EMAIL')
        mongo_uri = get_required_env_var('DATABASE_URI')
        with MongoClientManager(mongo_uri) as client:
            logger.info_green(f"Checking if tenant {tenant_name} and user {tenant_mail} exist in the database.")
            count_name = count_documents(client, {"email": tenant_mail, "tenantId": tenant_name}, f"p81-{env_name}", "_User")
            if count_name < 1:
                raise RuntimeError(f"Tenant {tenant_name} and user {tenant_mail} do not exist in the database.")
            logger.info_green(f"Tenant {tenant_name} and user {tenant_mail} exist in the database.")
            query = {"tenantId": tenant_name, "status": {"$ne": "revoked"}}
            count_access = count_documents(client, query, f"p81-{env_name}", "SupportAccess")
            if count_access < 1:
                raise RuntimeError(f"Support is not active for tenant {tenant_name}.")
            logger.info_green(f"Support is active for tenant {tenant_name}.")
            logger.info_green_bg("All checks passed successfully.")
    except Exception as e:
        # cannot use exit_on_error_and_write_summary because this will run in tc and not in github actions
        logger.error(f"failed to find tenant data in mongo: {e}")
        exit(1)


if __name__ == "__main__":
  main()