"""Import selected plain text as external evidence with an app-owned source grant."""

from __future__ import annotations

from datetime import datetime
from uuid import UUID

from pydantic import BaseModel, ConfigDict, TypeAdapter

from brain.client.application_conversations import ApplicationConversations
from brain.client.application_memory_contract import Reference
from brain.ingest.application_conversation_contract import canonical_hash


_REFERENCE = TypeAdapter(Reference)


class SelectedDocumentSource(BaseModel):
    """Create on the app server from an authorized person, project and source grant."""

    model_config = ConfigDict(extra="forbid", frozen=True)

    person: Reference
    project: Reference
    source_id: Reference

    def _id(self, kind: str, *parts: str) -> str:
        digest = canonical_hash([self.person, self.project, self.source_id, *parts])
        return f"document:{kind}:{digest.removeprefix('sha256:')}"

    @property
    def thread_id(self) -> str:
        return self._id("thread")

    def save(
        self, client: ApplicationConversations, *, document_id: str, change_id: str, text: str,
        occurred_at: datetime | str | None = None, expected_version_id: UUID | str | None = None,
    ) -> dict:
        """Save exact text. Keep the same change ID and arguments for explicit replay."""
        document_id = _REFERENCE.validate_python(document_id)
        change_id = _REFERENCE.validate_python(change_id)
        return client.save_message(
            external_id=self._id("item", document_id), thread_id=self.thread_id, case_id=self.project,
            role="system", text=text, occurred_at=occurred_at, expected_version_id=expected_version_id,
            idempotency_key=self._id("save", document_id, change_id),
        )

    def withdraw(
        self, client: ApplicationConversations, *, document_id: str, change_id: str,
        expected_version_id: UUID | str,
    ) -> dict:
        """Withdraw a current version after an authoritative removal or loss of access."""
        document_id = _REFERENCE.validate_python(document_id)
        change_id = _REFERENCE.validate_python(change_id)
        return client.withdraw_message(
            external_id=self._id("item", document_id), expected_version_id=expected_version_id,
            idempotency_key=self._id("withdraw", document_id, change_id),
        )

    def search(self, client: ApplicationConversations, *, query: str) -> dict:
        """Find current document evidence with the existing bounded lexical reader."""
        return client.task_context(query=query, thread_ids=[self.thread_id])

    def original(self, client: ApplicationConversations, *, version_id: UUID | str) -> dict:
        """Open a citation in this source. The app must still authorize the viewer."""
        reply = client.original(version_id)
        source = reply["original"]
        if source["thread_id"] != self.thread_id or source.get("case_id") != self.project:
            raise ValueError("original is outside the selected source")
        return reply
