# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-aaif-attestation-chain-forks-during-autonomous-credential-re-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-aaif-attestation-chain-forks-during-autonomous-credential-re-issuance.warrant.json
# Markdown SHA-256:   8c0369040838977b53b81d7d291aa6f2f188405f431311b55b62014828a41710
# Code AST SHA-256:   41bc093cade1068d4b58f2a58d522deafc56c0cda9cecb8633d820b07a659c76
# Verified Classes:   AttestationForkError, StaleTipError, Credential, AttestationLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class AttestationForkError(RuntimeError):
    """Raised when a self-issued credential would fork the attestation chain."""


class StaleTipError(AttestationForkError):
    """Raised when the issuer's claimed predecessor is not the log's current tip."""


@dataclass
class Credential:
    subject: str
    previous_hash: Optional[str]
    chain_depth: int
    issued_at: int
    not_after: int
    delegate_key: str

    def digest(self) -> str:
        payload = f"{self.subject}|{self.previous_hash}|{self.chain_depth}|{self.issued_at}|{self.delegate_key}"
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class AttestationLog:
    # subject -> current tip hash
    tips: dict[str, str] = field(default_factory=dict)
    # predecessor hash -> list of successor hashes (siblings reveal forks)
    successors: dict[str, list[str]] = field(default_factory=dict)
    entries: dict[str, Credential] = field(default_factory=dict)

    def tip_of(self, subject: str) -> Optional[str]:
        return self.tips.get(subject)

    def append(self, cred: Credential, claimed_tip: Optional[str]) -> str:
        actual_tip = self.tip_of(cred.subject)
        if claimed_tip != actual_tip:
            # The issuer believed a stale (or absent) predecessor was current.
            raise StaleTipError(
                f"issuer claimed predecessor {claimed_tip!r} but log tip is {actual_tip!r} "
                f"for subject {cred.subject!r}; refusing to fork chain at depth {cred.chain_depth}"
            )
        if cred.previous_hash is not None:
            siblings = self.successors.setdefault(cred.previous_hash, [])
            if siblings:
                raise AttestationForkError(
                    f"predecessor {cred.previous_hash!r} already has successor(s) {siblings!r}; "
                    f"predecessor-unique invariant violated"
                )
        h = cred.digest()
        self.entries[h] = cred
        if cred.previous_hash is not None:
            self.successors.setdefault(cred.previous_hash, []).append(h)
        self.tips[cred.subject] = h
        return h


def self_issue(
    log: AttestationLog,
    subject: str,
    delegate_key: str,
    now: int,
    context_tip: Optional[str],
    ttl: int = 2700,
) -> str:
    """
    Agent-initiated re-issuance. `context_tip` is what the agent *believes*
    the current tip is (from memory/compaction). The log enforces truth.
    """
    depth = 0
    prev = context_tip
    if prev is not None:
        if prev not in log.entries:
            raise StaleTipError(
                f"claimed predecessor {prev!r} is not present in attestation log; "
                f"context may reference a credential from a different lineage"
            )
        depth = log.entries[prev].chain_depth + 1
    cred = Credential(
        subject=subject,
        previous_hash=prev,
        chain_depth=depth,
        issued_at=now,
        not_after=now + ttl,
        delegate_key=delegate_key,
    )
    return log.append(cred, claimed_tip=context_tip)


def audit_chain(log: AttestationLog, subject: str) -> list[str]:
    """Replay from root; detect any predecessor with multiple successors."""
    forks = [p for p, succ in log.successors.items() if len(succ) > 1]
    if forks:
        raise AttestationForkError(
            f"attestation chain for {subject!r} is forked at predecessor(s) {forks!r}"
        )
    return [h for h, c in log.entries.items() if c.subject == subject]
