"""
Retrieval Domain Receipts

Receipt types for retrieval operations and knowledge lookups.

All retrieval receipts are Ed25519-signed, JCS-canonical, and linked to the
retrieval operations they record.

---
feature:
  id: feature.retrieval_receipts
  name: Retrieval Domain Receipts
  kind: module
  summary: Receipt models for retrieval operations
  owners: ["@agent-c"]
  stage: experimental
  tags: [receipts, retrieval, knowledge]
  depends_on: [feature.receipt_writer]
  inputs: [Retrieval operations, knowledge lookups]
  outputs: [Signed retrieval receipts in ledger]
  invariants:
    - All retrieval receipts are Ed25519-signed
    - Each retrieval is linked to its query context
---
"""

from __future__ import annotations

import logging
from typing import Any, Dict, List, Optional

from pydantic import Field

from receipts.base import BaseReceipt

logger = logging.getLogger(__name__)


class RetrievalReceipt(BaseReceipt):
    """
    Emitted when a retrieval operation is performed.

    Provides audit trail for knowledge lookups and retrieval.
    """

    receipt_type: str = Field(default="RetrievalReceipt", alias="type")
    domain: str = Field(default="retrieval")

    # Query identity
    query_id: str = Field(description="Unique ID for this retrieval query")
    query_type: str = Field(default="semantic", description="Type of retrieval: semantic, keyword, hybrid")
    query_text: str = Field(description="The query text or pattern")

    # Results summary
    results_count: int = Field(default=0, description="Number of results returned")
    top_scores: List[float] = Field(default_factory=list, description="Relevance scores of top results")

    # Context
    source_collection: Optional[str] = Field(default=None, description="Which collection/index was queried")
    latency_ms: Optional[float] = Field(default=None, description="Retrieval latency in milliseconds")
    metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional retrieval metadata")

    # Policy/guard rails
    retrieval_policy_id: Optional[str] = Field(
        default=None, description="Policy version applied to this retrieval"
    )
    retrieval_profile: Optional[str] = Field(
        default=None, description="Profile used for retrieval permissions"
    )
    subject_id: Optional[str] = Field(default=None, description="Subject of the retrieval")
    tenant_id: Optional[str] = Field(default=None, description="Tenant of the retrieval")
    returned_episode_ids: List[str] = Field(
        default_factory=list, description="Episode IDs returned to the caller"
    )
    returned_receipt_ids: List[str] = Field(
        default_factory=list, description="Receipt IDs returned to the caller"
    )
