"""Stable contracts for the local mySecondBrain26 knowledge plane.

Document bytes, extracted text, and model-generated summaries are deliberately
different kinds of data.  These contracts keep provenance, trust and sensitivity
attached to each item so a future retriever cannot treat document content as an
instruction or silently send it to a remote model.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Protocol, runtime_checkable


class DocumentTrust(str, Enum):
    """How the source entered the library; never an execution permission."""

    UNTRUSTED = "untrusted"
    EXTERNAL = "external"
    REVIEWED = "reviewed"
    TRUSTED = "trusted"


class Sensitivity(str, Enum):
    """Conservative data-handling label for a document and its derivatives."""

    PUBLIC = "public"
    PERSONAL = "personal"
    SENSITIVE = "sensitive"
    RESTRICTED = "restricted"


class DocumentStatus(str, Enum):
    """Lifecycle state before a document can be used for retrieval."""

    REGISTERED = "registered"
    QUARANTINED = "quarantined"
    EXTRACTED = "extracted"
    INDEXED = "indexed"
    FAILED = "failed"


@dataclass(frozen=True)
class KnowledgeSource:
    """One explicitly approved origin from which documents may be registered."""

    source_id: str
    source_uri: str
    trust: DocumentTrust = DocumentTrust.EXTERNAL
    sensitivity: Sensitivity = Sensitivity.PERSONAL
    approved: bool = False
    metadata: dict[str, Any] = field(default_factory=dict)


@dataclass(frozen=True)
class DocumentRegistration:
    """Metadata needed to register one immutable document version.

    ``content`` is used only to calculate the local integrity digest.  This
    contract does not persist or transmit bytes; an origin-store adapter will
    be introduced separately and must have its own retention and backup policy.
    """

    source: KnowledgeSource
    content: bytes
    media_type: str
    metadata: dict[str, Any] = field(default_factory=dict)


@dataclass(frozen=True)
class KnowledgeDocument:
    """Persisted metadata for an idempotently registered document version."""

    document_id: str
    source_id: str
    source_uri: str
    content_sha256: str
    media_type: str
    trust: DocumentTrust
    sensitivity: Sensitivity
    status: DocumentStatus
    metadata: dict[str, Any]
    created_at: float
    updated_at: float
    # Temporal validity fields (MemStrata pattern)
    valid_from: float = 0.0
    valid_to: float = 0.0
    superseded_by: str = ""


@runtime_checkable
class KnowledgeRepository(Protocol):
    """Repository boundary for document metadata, independent of indexes."""

    def register(self, registration: DocumentRegistration) -> tuple[KnowledgeDocument, bool]:
        """Return a document and whether this call created it."""
        ...

    def get(self, document_id: str) -> KnowledgeDocument | None:
        """Return a document by its stable identifier."""
        ...


@dataclass(frozen=True)
class KG1Node:
    """Instance Resource Graph node — Jurassic OiO-pattern business ontology element."""

    id: str
    type: str  # "entity" | "relationship" | "rule" | "resource"
    source: KnowledgeSource
    business_semantics: dict[str, Any] = field(default_factory=dict)
    domain_constraints: dict[str, Any] = field(default_factory=dict)
    evidence: list[dict[str, Any]] = field(default_factory=list)
    metadata: dict[str, Any] = field(default_factory=dict)


__all__ = [
    "DocumentRegistration",
    "DocumentStatus",
    "DocumentTrust",
    "KG1Node",
    "KnowledgeDocument",
    "KnowledgeRepository",
    "KnowledgeSource",
    "Sensitivity",
]
