"""Build mode helpers — silent (MDM Python-only) vs visible (Electron + Python)."""

from functools import lru_cache

from ws_package.log.writer import LogWriter

logger = LogWriter.file(__name__)

SILENT_DEFAULT_PROJECT_ID = "1001"
SILENT_DEFAULT_TASK_ID = "0"


def _parse_build_mode(raw) -> str:
    """Normalize [System] build= value (first token only; ignores inline comments)."""
    if raw is None:
        return "visible"
    text = str(raw).strip().lower()
    if not text:
        return "visible"
    # INI values must not contain inline comments; tolerate "silent — note" mistakes.
    token = text.split()[0].split(";")[0].split("#")[0]
    if token.startswith("silent"):
        return "silent"
    return "visible"


@lru_cache(maxsize=1)
def is_silent_build() -> bool:
    """True when [System] build=silent in config.ini (MDM / standalone agent)."""
    raw = None
    try:
        from ws_package.configs import config

        raw = config("build", "System")
        mode = _parse_build_mode(raw)
    except Exception:
        mode = "visible"
    logger.info("[BuildMode] config [System] build=%r → mode=%s", raw, mode)
    return mode == "silent"


def clear_build_mode_cache() -> None:
    is_silent_build.cache_clear()


def read_build_mode_at_import() -> str:
    """Read [System] build= without starting the config watchdog (module import time)."""
    import configparser
    from importlib.resources import as_file, files

    try:
        config_resource = files("ws_package").joinpath("config.ini")
        with as_file(config_resource) as config_path:
            parser = configparser.ConfigParser()
            parser.read(str(config_path))
            raw = parser.get("System", "build", fallback="visible")
            return _parse_build_mode(raw)
    except Exception:
        return "visible"


def apply_org_to_activity(activity, org_entity) -> None:
    """Apply OrgEntity fields onto ActivityController (shared by visible fallback + silent)."""
    if activity is None or org_entity is None:
        return

    interval = {"5 Min.": 300, "15 Min.": 900}.get(org_entity.timeInterval, 600)

    activity.org_id = org_entity.org_id
    activity.screenshot_interval = org_entity.ssfrequencystatus
    activity.interval = interval
    activity.appandurlstatus = org_entity.appandurlstatus
    activity.blur_intensity = org_entity.screenshotblurstatus
    activity.org_api_timezone = getattr(org_entity, "user_timezone", None)
    if getattr(org_entity, "notification_status", None) is not None:
        activity.notification_status = org_entity.notification_status
    if getattr(org_entity, "idle_time_limit_in_seconds", None) is not None:
        activity.idle_time_limit_in_seconds = org_entity.idle_time_limit_in_seconds
    if getattr(org_entity, "limit_action", None) is not None:
        activity.limit_action = org_entity.limit_action

    from ws_package.entities.org_entity import normalize_timezone_preference

    preference = normalize_timezone_preference(
        getattr(org_entity, "timezone_preference", 1)
    )
    activity.timezone_preference = preference
    user_entity = getattr(activity, "user_entity", None)
    if user_entity is not None:
        user_entity.timezone_preference = preference

    logger.info(
        "[BuildMode] Applied org settings to activity: org_id=%s interval=%ss timezone_preference=%s",
        org_entity.org_id,
        activity.interval,
        preference,
    )
