from configparser import ConfigParser
from defence360agent.utils import is_cloudways
from im360.utils import coraza_for_cloudways_hybrid_flag

# This code is a ported copy-paste from Go agent.


def _get_server_type(path: str, raise_err: bool) -> str:
    try:
        cfg = ConfigParser()
        cfg.read(path)
        return cfg.get("web_server", "server_type", fallback="")
    except Exception:
        if raise_err:
            raise
    return ""


def _is_nginx_server(path: str, raise_err: bool) -> bool:
    return _get_server_type(path, raise_err) == "nginx"


def is_force_use_coraza(
    *,
    path: str = "/etc/sysconfig/imunify360/integration.conf",
    raise_err: bool = False,
    detect_cloudways: bool = True,
) -> bool:
    if not _is_nginx_server(path, raise_err):
        return False
    if detect_cloudways:
        return is_cloudways()
    return True


def is_cloudways_hybrid(
    *,
    path: str = "/etc/sysconfig/imunify360/integration.conf",
    raise_err: bool = False,
    detect_cloudways: bool = True,
) -> bool:
    if _get_server_type(path, raise_err) != "apache":
        return False
    if not coraza_for_cloudways_hybrid_flag():
        return False
    if detect_cloudways:
        return is_cloudways()
    return True


def generic_panel_uses_coraza() -> bool:
    return is_force_use_coraza() or is_cloudways_hybrid()
