import sys, os

# cPanel Phusion Passenger WSGI entrypoint
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
if CURRENT_DIR not in sys.path:
    sys.path.insert(0, CURRENT_DIR)

# Load private settings from .env (same folder). Values already set in the
# cPanel "Environment variables" section take priority over the file.
def _load_env_file(path):
    try:
        with open(path, encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                key, value = line.split("=", 1)
                key, value = key.strip(), value.strip().strip('"').strip("'")
                if key and value:
                    os.environ.setdefault(key, value)
    except FileNotFoundError:
        pass

_load_env_file(os.path.join(CURRENT_DIR, ".env"))

# Crucial for Linux / cPanel hosting: enables Linux-compatible secure storage
os.environ.setdefault("MX_ALLOW_INSECURE_DEV_STORE", "1")
os.environ.setdefault("MX_APP_VERSION", "4.0.2")

# Import the Flask application
try:
    from mx_admin_credential_setup import configure_once
    configure_once()
    from mx_web_admin import app as application
    application.config['SESSION_COOKIE_SECURE'] = True
except Exception as e:
    import traceback
    _err = traceback.format_exc()
    def application(environ, start_response):
        status = '500 Internal Server Error'
        print(_err, file=sys.stderr)
        output = b"Admin could not start. Check the private server error log."
        response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))]
        start_response(status, response_headers)
        return [output]
