"""Deterministic lease and SQLite fencing experiment.

The lease is a small model, not a Redis or etcd implementation. Run with
``python3 lease_and_fence.py``; only Python's standard library is required.
"""

import sqlite3
import sys
from dataclasses import dataclass


@dataclass(frozen=True)
class Grant:
    owner: str
    fence: int
    expires_at: int


class LeaseModel:
    def __init__(self) -> None:
        self.current: Grant | None = None
        self.next_fence = 0

    def acquire(self, owner: str, now: int, ttl: int) -> Grant:
        if ttl <= 0:
            raise ValueError("ttl must be positive")
        if self.current is not None and now < self.current.expires_at:
            raise ValueError("lease is still active")
        self.next_fence += 1
        self.current = Grant(owner, self.next_fence, now + ttl)
        return self.current

    def release(self, grant: Grant, now: int) -> bool:
        if self.current != grant or now >= grant.expires_at:
            return False
        self.current = None
        return True


def create_database() -> sqlite3.Connection:
    db = sqlite3.connect(":memory:")
    db.execute(
        "CREATE TABLE settlement ("
        "day TEXT PRIMARY KEY, total INTEGER NOT NULL, fence INTEGER NOT NULL)"
    )
    return db


def write_without_fence(db: sqlite3.Connection, total: int, fence: int) -> None:
    db.execute(
        "INSERT INTO settlement(day, total, fence) VALUES('2026-11-23', ?, ?) "
        "ON CONFLICT(day) DO UPDATE SET "
        "total=excluded.total, fence=excluded.fence",
        (total, fence),
    )


def write_with_fence(db: sqlite3.Connection, total: int, fence: int) -> int:
    cursor = db.execute(
        "INSERT INTO settlement(day, total, fence) VALUES('2026-11-23', ?, ?) "
        "ON CONFLICT(day) DO UPDATE SET "
        "total=excluded.total, fence=excluded.fence "
        "WHERE excluded.fence > settlement.fence",
        (total, fence),
    )
    return cursor.rowcount


def current(db: sqlite3.Connection) -> tuple[int, int]:
    row = db.execute(
        "SELECT total, fence FROM settlement WHERE day='2026-11-23'"
    ).fetchone()
    assert row is not None
    return row


def main() -> None:
    print("Python/SQLite:", sys.version.split()[0], sqlite3.sqlite_version)
    lease = LeaseModel()
    a = lease.acquire("task-a", now=0, ttl=30)
    # A pauses. B can acquire at t=31. A's stale release cannot remove B.
    b = lease.acquire("task-b", now=31, ttl=30)
    old_release = lease.release(a, now=32)
    assert not old_release and lease.current == b
    print("A release after B acquired:", old_release)
    print("tokens A/B:", a.fence, b.fence)

    naive = create_database()
    write_without_fence(naive, total=200, fence=b.fence)
    write_without_fence(naive, total=100, fence=a.fence)
    print("unprotected B then A:", current(naive))
    assert current(naive) == (100, a.fence)

    protected = create_database()
    first = write_with_fence(protected, total=200, fence=b.fence)
    stale = write_with_fence(protected, total=100, fence=a.fence)
    same_token_change = write_with_fence(protected, total=999, fence=b.fence)
    print("protected B/A/same-token rowcounts:", first, stale, same_token_change)
    print("protected final:", current(protected))
    assert (first, stale, same_token_change) == (1, 0, 0)
    assert current(protected) == (200, b.fence)

    # An old write may arrive first. Fencing stops later regression but does
    # not promise that readers never see the old intermediate result.
    old_first = create_database()
    first_old = write_with_fence(old_first, total=100, fence=a.fence)
    intermediate = current(old_first)
    later_new = write_with_fence(old_first, total=200, fence=b.fence)
    print("A first, before B:", first_old, intermediate)
    print("A first, after B:", later_new, current(old_first))
    assert first_old == later_new == 1
    assert intermediate == (100, a.fence)
    assert current(old_first) == (200, b.fence)


if __name__ == "__main__":
    main()
