"""Pipeline isolation primitives.

Turn 3 (2026-10-10). Companion to design/ISOLATION-v1.0.md.

Standards:
  Kleppmann, DDIA 2017 Ch. 7       (optimistic concurrency)
  Fowler, PoEAA 2002 Ch. 11        (Unit of Work)
  AWS Well-Architected REL05-BP01  (Cell-Based Architecture)
  Azure Architecture Center        (Bulkhead Pattern)
  ISO/IEC 27001 A.8.3              (row-level isolation)
  MySQL 8.0 Ref. Manual 15.7.2     (InnoDB row-level locking)
  Rules 23, 24, 25, 28
"""

from contextlib import contextmanager

from django.db import transaction

from exams.models import TaskPipeline


class PipelineIsolatedManager:
    """Read wrapper that refuses operations without explicit pipeline scope.

    Every maintenance read MUST go through for_pipeline().
    Bulk reads MUST use all_pipelines() with a reason >= 20 chars.
    """

    def __init__(self, model):
        self.model = model

    def for_pipeline(self, pipeline_id):
        if not pipeline_id:
            raise ValueError("pipeline_id required (Rule 25: one task one owner)")
        return self.model.objects.filter(pipeline_id=pipeline_id)

    def all_pipelines(self, reason):
        if not reason or len(reason.strip()) < 20:
            raise ValueError(
                "all_pipelines() requires reason >= 20 chars. "
                "This is the Rule 28 command-isolation guard."
            )
        return self.model.objects.all()


@contextmanager
def with_pipeline_lock(pipeline_id):
    """Lock ONE pipeline row for update.

    Caller MUST be inside transaction.atomic().
    Only the target row is locked. Other pipelines continue.

    Usage:
        with transaction.atomic():
            with with_pipeline_lock(pid) as p:
                p.version += 1
                p.save(update_fields=['version'])
    """
    if not transaction.get_connection().in_atomic_block:
        raise RuntimeError(
            "with_pipeline_lock must be called inside transaction.atomic(). "
            "Fowler Unit of Work (PoEAA Ch. 11)."
        )
    p = TaskPipeline.objects.select_for_update().get(id=pipeline_id)
    yield p
