# `with` and context managers, as Python runs them: `__enter__` gives what `as` binds,
# `__exit__` runs however the body ends (at its end, by `return`, `break` or `continue`, or by
# an exception, which it is given and which it suppresses by returning True), and several
# items nest
from dataclasses import dataclass

from verada import raises


class Refused(Exception):
    pass


@dataclass
class Log:
    name: str
    open: bool = False
    lines: int = 0
    swallow: bool = False

    def __enter__(self) -> Log:
        self.open = True
        print("enter", self.name)
        return self

    def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: object) -> bool:
        print("exit", self.name, "lines", self.lines, "exception" if exc_type is not None else "none", exc)
        self.open = False
        return self.swallow


# a manager whose `__enter__` gives another value, and whose `__exit__` returns nothing
@dataclass
class Ticket:
    used: bool = False

    def __enter__(self) -> int:
        self.used = True
        return 7

    def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: object) -> None:
        self.used = False


# a manager that changes nothing of its own: `__exit__` only reports
@dataclass
class Note:
    text: str

    def __enter__(self) -> Note:
        return self

    def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: object) -> None:
        print("note", self.text, exc)


def plain() -> None:
    # the name is the manager: what the body does to it, `__exit__` sees, and after it too
    with Log("plain") as log:
        log.lines = 2
        print("inside", log.open)
    print("after", log.open, log.lines)


def quiet() -> None:
    raises({Refused: True})
    with Log("quiet", swallow=True) as q:
        q.lines = 1
        raise Refused("suppressed")
    print("after quiet", q.open)


def loud() -> None:
    raises({Refused: True})
    with Log("outer") as a, Log("inner") as b:
        a.lines = 1
        b.lines = 5
        raise Refused("goes on")


# the value a `return` gives is the one it had before `__exit__` ran
def first_negative(xs: list[int]) -> int:
    t = Ticket()
    for i in range(len(xs)):
        with t as n:
            if xs[i] < 0 and n > 0:
                return i
    return -1


def scan(xs: list[int]) -> None:
    for i in range(len(xs)):
        with Log("scan") as log:
            log.lines = 1
            if xs[i] < 0:
                print("negative at", i)
                return
            if xs[i] == 0:
                break
            if xs[i] == 1:
                continue
            print("looked at", xs[i])
    print("scan ended")


def main() -> None:
    plain()
    try:
        quiet()
        loud()
    except Refused as e:
        print("caught", e)
    print(first_negative([3, 1, -4, 2]))
    print(first_negative([3, 0, 4]))
    scan([3, 1, -4, 2])
    scan([3, 0, -4])
    with Note("done"):
        print("last")


if __name__ == "__main__":
    main()
