# APL in Vibe (T32c): `apl("...")` is a plain call, so the file stays valid Python; Verada
# reads the text as in Vada and Varc (apl-variant.md 5.4). Arrays index from 0, as `⍳` does.
from itertools import accumulate

from verada import *


# (a subtype of `int`, so APL's arithmetic on its values is `int`'s)
type Small = Annotated[int, Interval(ge=-100, le=100)]


class Vector(Array[Small], rank=1):
    pass


class Values(Array[int], rank=1):
    pass


class Matrix(Array[Small], rank=2):
    pass


class Grid(Array[int], rank=2):
    pass


def mean(x: Vector) -> int:
    requires(1 <= len(x) and len(x) <= 1000)
    return apl("⌊ (+/ x) ÷ ≢ x")


def dot(x: Vector, y: Vector) -> int:
    requires(len(x) == len(y) and len(x) <= 1000)
    return apl("+/ x × y")


def largest(x: Vector) -> int:
    return apl("⌈/ x")


def above(x: Vector, limit: Small) -> Values:
    requires(len(x) <= 1000)
    return apl("(x > limit) / x")


def common(x: Vector, y: Vector) -> Values:
    requires(len(x) <= 1000 and len(y) <= 1000)
    return apl("(x ∊ y) / x")


def places(x: Vector, y: Vector) -> Values:
    requires(len(x) <= 1000)
    return apl("x ⍳ y")


def running_sums(x: Vector) -> Values:
    requires(len(x) <= 1000)
    return accumulate(x)


def running(x: Vector) -> Values:
    requires(len(x) <= 1000)
    return apl(r"+\ x")


def reversed_of(x: Vector) -> Values:
    return apl("⌽ x")


def table(n: int) -> Grid:
    requires(0 <= n and n <= 10)
    ensures(result.shape[0] == n and result.shape[1] == n)
    return apl("(1 + ⍳ n) ∘.× 1 + ⍳ n")


def product(a: Matrix, b: Matrix) -> Grid:
    requires(a.shape[1] == b.shape[0] and a.shape[0] <= 10 and a.shape[1] <= 10 and b.shape[1] <= 10)
    ensures(result.shape[0] == a.shape[0] and result.shape[1] == b.shape[1])
    return apl("a +.× b")


def product_at(a: Matrix, b: Matrix) -> Grid:
    requires(a.shape[1] == b.shape[0] and a.shape[0] <= 10 and a.shape[1] <= 10 and b.shape[1] <= 10)
    ensures(result.shape[0] == a.shape[0] and result.shape[1] == b.shape[1])
    return a @ b


def transposed(m: Matrix) -> Grid:
    ensures(result.shape[0] == m.shape[1] and result.shape[1] == m.shape[0])
    return m.T


def row_totals(m: Matrix) -> Values:
    requires(m.shape[1] <= 10)
    return apl("+/ m")
