"""I-Logic Primitive - O(1) State Multiplication

Verified: 11/11 tests, 125 combinations.

5 states: DIRECT (1), INVERSE (-1), SPIRAL (+i), ANTI_SPIRAL (-i), ABSORBED (0)
"""
from ..i_logic.states import ILogicState
from ..i_logic.algebra import multiply as _multiply, compose as _compose, detect_cycle as _detect_cycle


def multiply(a: str, b: str) -> str:
    """O(1) state multiplication.

    Args:
        a: State name (DIRECT, INVERSE, SPIRAL, ANTI_SPIRAL, ABSORBED)
        b: State name

    Returns:
        Result state name
    """
    state_a = ILogicState.from_name(a)
    state_b = ILogicState.from_name(b)
    if state_a is None or state_b is None:
        raise ValueError(f"Unknown state: {a} or {b}")
    result = _multiply(state_a, state_b)
    return ILogicState.name(result)


def compose(states: list) -> tuple:
    """O(N) path composition with early termination.

    Args:
        states: List of state names

    Returns:
        (final_state_name, steps_taken)
    """
    parsed = []
    for s in states:
        state = ILogicState.from_name(s)
        if state is None:
            raise ValueError(f"Unknown state: {s}")
        parsed.append(state)

    result, steps = _compose(parsed)
    return ILogicState.name(result), steps


def detect_cycle(states: list) -> tuple:
    """Detect if path cycles.

    Args:
        states: List of state names

    Returns:
        (is_cycle, description, period)
    """
    parsed = []
    for s in states:
        state = ILogicState.from_name(s)
        if state is None:
            raise ValueError(f"Unknown state: {s}")
        parsed.append(state)

    return _detect_cycle(parsed)
