# -*- coding: utf-8 -*-
"""utils.activation_flag_validator — real merge executor activation flag.

task-2637 — real merge executor wiring 코드화 (activation false default · 실제 merge 실행 0).

Spec: memory/specs/system_real_merge_executor_wiring_spec_260523.md
sha256: bcaf654e981a43083af50879164021c918eeac9753cad3b3ad146209a1a62765

회장 verbatim (spec §6 / task-2637 회장 10결정 #1):
    ACTIVATION_FLAG_DEFAULT = False (hardcoded · 런타임 변경 0)
    activation = env_var + chair_authorization JSON 둘 다 필요.
    둘 중 하나라도 없으면 NO_OP_NO_AUTHORIZATION.

ANCHOR-2 (task md §"frozen anchor"):
    "activation_flag default=False hardcoded · chair_authorization 부재 시
     NO_OP_NO_AUTHORIZATION · 둘 다 True 일 때만 11종 gate 재검증"
"""
from __future__ import annotations

import os
from typing import Callable, Optional

ACTIVATION_FLAG_DEFAULT: bool = False
ACTIVATION_FLAG_ENV_VAR = "ANU_REAL_MERGE_EXECUTOR_ACTIVE"

# Import-time assertion (spec §6.3): the hardcoded default MUST be False.
# Any source-level edit that flips this constant to True will fail import
# loudly — runtime mutation is impossible because the constant is bound here.
assert ACTIVATION_FLAG_DEFAULT is False, (
    "ACTIVATION_FLAG_DEFAULT must remain False at module load "
    "(spec §6.3 default OFF doctrine)"
)


_TRUE_TOKENS = frozenset({"1", "true", "TRUE", "True", "on", "ON", "yes", "YES"})


def _env_lookup(env_lookup: Optional[Callable[[str], Optional[str]]]) -> Callable[[str], Optional[str]]:
    return env_lookup if env_lookup is not None else os.environ.get


def resolve_activation_flag(
    env_lookup: Optional[Callable[[str], Optional[str]]] = None,
) -> bool:
    """Return the resolved activation flag (spec §6).

    Resolution rules (fail-closed):
      * Default is ``ACTIVATION_FLAG_DEFAULT`` (False) at all times.
      * If the env var ``ANU_REAL_MERGE_EXECUTOR_ACTIVE`` is set to one of the
        known truthy tokens, the flag is True. Any other value, including the
        string "false"/"0"/"", returns False.
      * The env var is intended for chair-explicit setup only. ``register the
        env value at activate-time + chair_authorization JSON`` is the only
        path that produces True (spec §6.3).
    """
    lookup = _env_lookup(env_lookup)
    raw = lookup(ACTIVATION_FLAG_ENV_VAR)
    if raw is None:
        return ACTIVATION_FLAG_DEFAULT
    return str(raw) in _TRUE_TOKENS


def assert_default_off() -> None:
    """Defensive re-check used by regression tests and the dispatch wiring.

    Always re-asserts that the hardcoded default is False. Raises
    ``AssertionError`` if a hostile patch somehow mutated the constant; the
    real merge executor must never proceed past this assertion.
    """
    assert ACTIVATION_FLAG_DEFAULT is False, (
        "ACTIVATION_FLAG_DEFAULT mutated from False — abort real merge "
        "executor (spec §6.3 ANCHOR-2)"
    )
