# Copyright 2024 Klira AI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Guideline context variable for transparent guideline propagation.

Stores guardrail guidelines in a contextvars.ContextVar so they can flow
from the @guardrails decorator to LLM adapters without parameter passing.

Architecture: decorator produces → context var stores → adapter consumes & clears.
"""

from __future__ import annotations

import contextvars

_guidelines_var: contextvars.ContextVar[list[str] | None] = contextvars.ContextVar(
    "klira_guidelines", default=None
)


def set_current_guidelines(guidelines: list[str]) -> contextvars.Token[list[str] | None]:
    """Store guidelines in the context variable.

    Args:
        guidelines: List of guideline strings from guardrail evaluation.

    Returns:
        Token for restoring the previous value via clear_current_guidelines.
    """
    return _guidelines_var.set(guidelines)


def get_current_guidelines() -> list[str] | None:
    """Read current guidelines from the context variable.

    Returns:
        The current guidelines list, or None if no guidelines are active.
    """
    return _guidelines_var.get()


def reset_current_guidelines() -> None:
    """Clear guidelines without a token (used by adapters after consumption)."""
    _guidelines_var.set(None)


def clear_current_guidelines(token: contextvars.Token[list[str] | None]) -> None:
    """Reset guidelines to the previous value using the token.

    Args:
        token: Token returned by set_current_guidelines.
    """
    _guidelines_var.reset(token)
