"""Canonical one-row semantic reissue executor."""

from __future__ import annotations

from dataclasses import dataclass

from .contract import SOURCE_FILE_DIGEST, SOURCE_ROW_DIGEST, canonical_source_frame
from .store import OperationsStore, ReissueOperation, StoreError


@dataclass(frozen=True, slots=True)
class ExecutionResult:
    """Exact durable row outcome."""

    row_digest: str
    frame_sha256: str
    appended: bool


def canonical_reissue(
    source: OperationsStore,
    target: OperationsStore,
    *,
    recovery: bool = False,
) -> ExecutionResult:
    """Read one authenticated source row and append or replay through the installed store."""
    source_rows = source.read()
    target_rows = target.read()
    if len(source_rows) != 1 or source_rows[0].canonical_frame() != canonical_source_frame():
        raise StoreError("source history is not the sole authenticated frame")
    if target_rows and (not recovery or target_rows != source_rows):
        raise StoreError("target is not an admitted empty or exact recovery history")
    outcome = target.append(ReissueOperation(source_rows[0]))
    if outcome.appended is recovery:
        raise StoreError("installed append/replay disposition")
    if outcome.row != source_rows[0] or outcome.row.row_digest != SOURCE_ROW_DIGEST:
        raise StoreError("installed append changed row semantics")
    if outcome.row.canonical_frame() != canonical_source_frame():
        raise StoreError("installed append changed canonical bytes")
    return ExecutionResult(SOURCE_ROW_DIGEST, SOURCE_FILE_DIGEST, True)
