from __future__ import annotations

from datetime import UTC, datetime
from typing import Literal

from pydantic import Field

from app.models.common import StrictModel


class QueryLogEntry(StrictModel):
    request_id: str
    user_id: str | None = None
    repo_id: str
    snapshot_id: str
    question: str
    intent_type: str
    intent_tier: Literal["tier1", "tier2"]
    model: str | None = None
    hit_count: int
    latency_ms: int
    streamed: bool
    status: Literal[
        "success",
        "error",
        "no_context",
        "general_fallback",
        "guardrail_refused",
        "commit_history_unavailable",
    ]
    error_message: str | None = None
    guardrail_action: str | None = None
    guardrail_finding_counts: dict[str, int] = Field(default_factory=dict)
    guardrail_context_redacted_count: int = 0
    guardrail_context_blocked_count: int = 0
    guardrail_output_refused: bool = False
    retrieval_fallback_used: bool = False
    retrieval_fallback_pass: str | None = None
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))

    def to_document(self) -> dict:
        doc = self.model_dump(mode="json")
        doc["created_at"] = self.created_at
        return doc
