"""SRL Primitive - O(1) Integer Square Root

Verified: 0% error, distance up to 10^9, <=25 iterations.

The SRL formula: t = d/t -> t^2 = d -> t = sqrt(d)
Loop is INSIDE the unit - self-reference stabilized.
"""
from .._core import srl_sqrt


def sqrt(distance: int) -> int:
    """O(1) integer square root via Newton-Raphson.

    Guaranteed <=25 iterations for any distance up to 10^9.
    """
    return srl_sqrt(distance)


def validate(distance: int) -> dict:
    """Validate SRL sqrt for a distance.

    Returns dict with:
        - input: original distance
        - result: computed sqrt
        - squared: result * result
        - error: absolute error
        - valid: whether error is within bounds
    """
    result = sqrt(distance)
    squared = result * result

    # For integer sqrt, result^2 <= distance < (result+1)^2
    error = abs(squared - distance)
    valid = squared <= distance < (result + 1) * (result + 1)

    return {
        "input": distance,
        "result": result,
        "squared": squared,
        "error": error,
        "valid": valid
    }


def time_scale(distance: int) -> int:
    """Convert distance to time scale: t = sqrt(d)."""
    return sqrt(distance)
