"""
reasoning.py — Auto-reasoning injection helpers.

Shared by both interceptor.py and client.py to avoid circular imports.
"""

REASONING_INSTRUCTION = (
    'When making a decision, include a "reasoning_steps" field in your JSON response '
    '-- an array where each item has: "factor" (the field or signal you considered), '
    '"value" (the actual value you saw), "signal" ("risk" or "safe"), and "explanation" '
    '(one sentence). Example: {"factor":"credit_score","value":"748","signal":"safe",'
    '"explanation":"Above minimum threshold of 680."}'
)


def inject_auto_reasoning_messages(messages: list, config: dict) -> list:
    """
    Inject auto-reasoning instruction into an OpenAI-style messages array.

    Rules:
    - autoReasoning explicitly False in config -> return unchanged
    - Any message already mentions 'reasoning_steps' -> return unchanged (developer has it)
    - System message exists -> append instruction at end
    - No system message -> prepend one

    Never mutates the original list.
    """
    if config.get("autoReasoning") is False:
        return messages
    if not messages:
        return messages

    for m in messages:
        content = m.get("content", "") if isinstance(m, dict) else str(m)
        if "reasoning_steps" in (content or ""):
            return messages

    msgs = list(messages)
    sys_idx = next(
        (i for i, m in enumerate(msgs) if isinstance(m, dict) and m.get("role") == "system"),
        -1
    )

    if sys_idx != -1:
        existing = msgs[sys_idx].get("content", "")
        msgs[sys_idx] = {**msgs[sys_idx], "content": existing + "\n\n" + REASONING_INSTRUCTION}
    else:
        msgs = [{"role": "system", "content": REASONING_INSTRUCTION}] + msgs

    return msgs


def inject_auto_reasoning_system(system: str, config: dict) -> str:
    """
    Inject auto-reasoning instruction into an Anthropic-style system string.

    Rules:
    - autoReasoning explicitly False -> return unchanged
    - system already contains 'reasoning_steps' -> return unchanged
    - Otherwise append (or create) instruction
    """
    if config.get("autoReasoning") is False:
        return system
    if system and "reasoning_steps" in system:
        return system
    if system:
        return system + "\n\n" + REASONING_INSTRUCTION
    return REASONING_INSTRUCTION
