"""Response models for the AmbientMeta SDK."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


@dataclass
class EntityResult:
    """A detected entity with its placeholder, type, and confidence."""

    placeholder: str
    type: str
    confidence: float


@dataclass
class BatchFeedbackResponse:
    """Response from the batch feedback endpoint."""

    accepted: int
    correction_ids: list[str]
    contradictions_detected: int = 0
    message: str = ""


@dataclass
class SanitizeResponse:
    """Response from the sanitize endpoint.

    Supports chained correction methods:
        result.correct("[PHONE_1]", "NPI").report_missed("EMP-123", "EMPLOYEE_ID").submit_corrections()
    """

    sanitized: str
    session_id: str | None
    entities_found: int
    entities: list[EntityResult]
    processing_ms: float
    redacted: bool = False

    # Internal — set by the client after construction, not part of the public API.
    _client: Any = field(default=None, repr=False)
    _corrections: list[dict[str, str]] = field(default_factory=list, repr=False)

    def correct(self, placeholder: str, correct_type: str) -> SanitizeResponse:
        """Mark a detected entity as misclassified. Accumulates for batch submit."""
        self._corrections.append({
            "placeholder": placeholder,
            "correct_type": correct_type,
            "feedback_type": "misclassification",
        })
        return self

    def report_missed(self, span_text: str, correct_type: str) -> SanitizeResponse:
        """Report an entity the system missed. Accumulates for batch submit."""
        self._corrections.append({
            "span_text": span_text,
            "correct_type": correct_type,
            "feedback_type": "missed_entity",
        })
        return self

    def report_false_positive(self, placeholder: str) -> SanitizeResponse:
        """Report a false positive detection. Accumulates for batch submit."""
        self._corrections.append({
            "placeholder": placeholder,
            "feedback_type": "false_positive",
        })
        return self

    def submit_corrections(self) -> BatchFeedbackResponse:
        """Submit all accumulated corrections (sync). Clears the list on success."""
        self._validate_corrections()
        result = self._client._send_batch_feedback_sync(
            session_id=self.session_id,
            corrections=list(self._corrections),
        )
        self._corrections.clear()
        return result

    async def asubmit_corrections(self) -> BatchFeedbackResponse:
        """Submit all accumulated corrections (async). Clears the list on success."""
        self._validate_corrections()
        result = await self._client._send_batch_feedback_async(
            session_id=self.session_id,
            corrections=list(self._corrections),
        )
        self._corrections.clear()
        return result

    def _validate_corrections(self) -> None:
        if not self._corrections:
            raise ValueError("No corrections to submit")
        if self._client is None:
            raise RuntimeError(
                "Cannot submit corrections: SanitizeResponse was not created by a client"
            )
        if self.session_id is None:
            raise ValueError(
                "Cannot submit corrections for redacted sessions (session_id is None)"
            )


@dataclass
class RehydrateResponse:
    """Response from the rehydrate endpoint."""

    text: str
    entities_restored: int
    processing_ms: float


@dataclass
class PatternResponse:
    """Response from the patterns endpoint."""

    pattern_id: str
    name: str
    status: str = "active"


@dataclass
class FeedbackResponse:
    """Response from the feedback endpoint."""

    status: str = "recorded"


@dataclass
class InsightItem:
    """A single insight from the insights endpoint."""

    id: str
    type: str
    title: str
    description: str | None = None
    status: str = "pending"
    data: dict[str, Any] = field(default_factory=dict)
    created_at: str = ""


@dataclass
class EntityStrength:
    """Entity type with its average detection confidence."""

    type: str
    confidence: float


@dataclass
class KnowledgeDepth:
    """CKD score and maturity metrics."""

    ckd_score: float = 0.0
    maturity: str = "nascent"
    strongest_entity: EntityStrength | None = None
    weakest_entity: EntityStrength | None = None
    contradictions_pending: int = 0
    contradictions_resolved: int = 0
    golden_set_size: int = 0
    compiled_rules: int = 0
    on_demand_hit_rate: float = 0.0


@dataclass
class DocumentJob:
    """A document redaction job."""

    job_id: str
    filename: str
    file_type: str
    status: str
    page_count: int | None = None
    total_entities: int = 0
    entity_counts: dict[str, int] = field(default_factory=dict)
    error_message: str | None = None
    processing_ms: float | None = None
    download_available: bool = False
    created_at: str = ""
    completed_at: str | None = None


@dataclass
class InsightsResponse:
    """Response from the insights endpoint."""

    pending_conflicts: list[InsightItem] = field(default_factory=list)
    proposed_improvements: list[InsightItem] = field(default_factory=list)
    discovered_patterns: list[InsightItem] = field(default_factory=list)
    knowledge_depth: KnowledgeDepth = field(default_factory=KnowledgeDepth)
