"""Tenant-settings helpers — the books-ownership flag (ADR #021).

``tenants.settings.books_owner`` says who owns a tenant's books:

  - ``"sheet"`` — the nightly rebuild re-imports this tenant's books from
    the sheet export (clear + reimport) and in-app invoice/expense writes
    are refused (an edit would look saved, then vanish at the rebuild).
  - ``"app"``   — the nightly leaves this tenant's rows untouched and
    in-app writes are allowed. The app is the system of record.
  - *absent*    — a legacy-mirrored tenant (Bowden Works): its rows are
    rebuilt nightly from ``legacy.*`` (NOT the sheet) and the books
    write-block does not apply (R1 rehearsal semantics, unchanged).

``books_owner`` supersedes the boolean ``parallel_run`` (ADR #019 →
ADR #021): a tenant that still carries only the legacy
``parallel_run: true`` is treated as ``"sheet"`` so nothing changes
behavior until the owner flips it (scripts/flip_books_owner.py).
"""

from __future__ import annotations

BOOKS_OWNER_SHEET = "sheet"
BOOKS_OWNER_APP = "app"


def effective_books_owner(settings: dict | None) -> str | None:
    """Resolve a tenant's effective books owner from its settings blob.

    Returns ``"sheet"``, ``"app"``, or ``None`` (legacy-mirrored / no
    books semantics). Back-compat: a missing ``books_owner`` plus a
    truthy legacy ``parallel_run`` reads as ``"sheet"``.
    """
    blob = settings or {}
    owner = blob.get("books_owner")
    if owner in (BOOKS_OWNER_SHEET, BOOKS_OWNER_APP):
        return owner
    if blob.get("parallel_run"):
        return BOOKS_OWNER_SHEET
    return None
