# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-artifact-chunk-as-non-durable-partial-result-streaming-across-org-boundaries-under-renegotiated-chunk-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-artifact-chunk-as-non-durable-partial-result-streaming-across-org-boundaries-under-renegotiated-chunk-windows.warrant.json
# Markdown SHA-256:   d02e7a466919046a0c0b6aa041b517a7bc4737662e4849aaf91b52583ccf6fa7
# Code AST SHA-256:   406de690d14e77fb19bb9cc2896734f5a6f096417ce4dfa7ee615ec27f6f475c
# Verified Classes:   DurabilityViolation, PartDurability, PersistedPart, ArtifactStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class DurabilityViolation(RuntimeError):
    """Raised when a consumer attempts to merge a persisted artifact part
    across an input-required boundary without producer continuation attestation."""


class PartDurability(Enum):
    DURABLE = "durable"
    PROVISIONAL = "provisional"


@dataclass
class PersistedPart:
    part_index: int
    content: str
    durability: PartDurability


@dataclass
class ArtifactStore:
    task_id: str
    artifact_id: str
    parts: dict[int, PersistedPart] = field(default_factory=dict)

    def highest_persisted_index(self) -> int:
        return max(self.parts) if self.parts else -1

    def demote_all_to_provisional(self) -> None:
        for p in self.parts.values():
            p.durability = PartDurability.PROVISIONAL


def reconcile_on_resume(
    store: ArtifactStore,
    resume_from: Optional[int],
) -> None:
    """Apply the decision boundary when a task re-enters `working`.

    resume_from is the producer's attested continuation index, if any.
    - None  -> no attestation: demote everything to provisional.
    - <= highest -> rewind: truncate persisted parts to resume_from - 1.
    - == highest + 1 -> continuation: keep durable parts as-is.
    - > highest + 1 -> gap: cannot merge, raise.
    """
    highest = store.highest_persisted_index()

    if resume_from is None:
        store.demote_all_to_provisional()
        return

    if resume_from <= highest:
        # Producer rewound; discard parts at or beyond the resume point.
        for idx in [i for i in store.parts if i >= resume_from]:
            del store.parts[idx]
        return

    if resume_from == highest + 1:
        # Explicit continuation across the boundary: persisted parts stand.
        return

    # resume_from > highest + 1 means the producer skipped indices we never saw.
    # Merging would leave a hole; refuse rather than emit a corrupt artifact.
    raise DurabilityViolation(
        f"task={store.task_id} artifact={store.artifact_id}: "
        f"producer resumed at index {resume_from} but consumer only holds up to "
        f"{highest}; cannot reconcile partial artifact across org boundary"
    )


def assemble_artifact(store: ArtifactStore) -> str:
    """Assemble only durable parts; refuse if any provisional part would be merged."""
    if any(p.durability is PartDurability.PROVISIONAL for p in store.parts.values()):
        raise DurabilityViolation(
            f"task={store.task_id} artifact={store.artifact_id}: "
            "refusing to assemble artifact containing provisional parts "
            "(unattested across input-required boundary)"
        )
    indices = sorted(store.parts)
    if indices != list(range(len(indices))):
        raise DurabilityViolation(
            f"task={store.task_id} artifact={store.artifact_id}: "
            f"non-contiguous part indices {indices}; artifact integrity unverifiable"
        )
    return "".join(store.parts[i].content for i in indices)
