"""Request-local cooperative limits; no timers, workers or global policy changes.

Outside scope() every helper preserves the existing manual behaviour.
An in-progress filesystem/library operation is not forcibly interrupted.
"""
from contextlib import contextmanager
from contextvars import ContextVar
import sqlite3
from time import perf_counter

OFFER_SECONDS = 30.0
NETWORK_SECONDS = 5.0
MAX_DATABASE = 64 * 1024 * 1024
_current = ContextVar('domestic_batch_limits', default=None)


class BatchStop(BaseException):
    # Deliberate control-flow exception: legacy broad `except Exception` must
    # not swallow a stop and continue into another expensive stage.
    def __init__(self, code, stage):
        self.code, self.stage = code, stage
        super().__init__({
            'budget_exhausted': 'Wyczerpano kooperatywny budżet 30 s. Nie rozpoczęto kolejnego etapu; uruchom ponownie.',
            'lock_busy': 'Zasób jest zajęty. Nie oczekiwano na blokadę; uruchom ponownie.',
            'database_limit': 'Wejściowa baza danych przekracza limit 64 MiB. Zatrzymano dalsze przetwarzanie.',
            'network_timeout': 'Przekroczono czas operacji sieciowej (do 5 s i pozostałego budżetu). Uruchom ponownie.',
        }[code])

    def result(self):
        return {'code': self.code, 'stage': self.stage, 'message': str(self)}


class Budget:
    def __init__(self):
        self.deadline = perf_counter() + OFFER_SECONDS

    def remaining(self):
        return self.deadline - perf_counter()

    def check(self, stage):
        if self.remaining() <= 0:
            raise BatchStop('budget_exhausted', stage)


def current():
    return _current.get()


@contextmanager
def scope():
    token = _current.set(Budget())
    try:
        yield
    finally:
        _current.reset(token)


def check(stage):
    budget = current()
    if budget is not None:
        budget.check(stage)


def network_timeout():
    budget = current()
    if budget is None:
        return 15.0  # unchanged manual dictionary timeout
    remaining = budget.remaining()
    if remaining <= 0:
        raise BatchStop('budget_exhausted', 'dictionary_network')
    return min(NETWORK_SECONDS, remaining)


@contextmanager
def locked(lock):
    if current() is None:
        with lock:
            yield
        return
    check('lock')
    if not lock.acquire(blocking=False):
        raise BatchStop('lock_busy', 'lock')
    try:
        check('lock')
        yield
    finally:
        lock.release()


def sqlite_options():
    return {'timeout': 0} if current() is not None else {}


def database(path, conn=None):
    if current() is None:
        return
    check('database_input')
    if path.stat().st_size > MAX_DATABASE:
        raise BatchStop('database_limit', 'database_input')
    if conn is not None:
        conn.execute('PRAGMA busy_timeout=0')
        pages = conn.execute('PRAGMA page_count').fetchone()[0]
        page_size = conn.execute('PRAGMA page_size').fetchone()[0]
        if pages * page_size > MAX_DATABASE:
            raise BatchStop('database_limit', 'database_input')
    check('database_input')


def raise_if_locked(exc):
    if current() is None:
        return
    if isinstance(exc, sqlite3.OperationalError) and getattr(exc, 'sqlite_errorcode', 0) & 255 in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED):
        raise BatchStop('lock_busy', 'sqlite') from exc


def backup(source, target, path):
    if current() is None:
        source.backup(target)
        return
    database(path, source)
    page_size = source.execute('PRAGMA page_size').fetchone()[0]
    def progress(status, remaining, total):
        check('database_backup')
        if status in (sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED):
            raise BatchStop('lock_busy', 'database_backup')
        if total * page_size > MAX_DATABASE:
            raise BatchStop('database_limit', 'database_backup')
    source.backup(target, pages=128, progress=progress, sleep=0.0)
    check('database_backup')
