"""SQL Server-backed storage for document/policy chunks and their embeddings.

Uses SQL Server's native `VECTOR` column type (SQL Server 2025+ / Azure SQL
-- confirmed against the actual target instance before this was written, not
assumed; see `VECTOR_DISTANCE('cosine', ...)` below) rather than a second
vector-search product. Two tables, one schema (`rag`), shared by both the
"documents" and "policies" collections -- collection is a column
(`documents.collection`), not a separate table pair, since the two
collections are structurally identical and only differ in access-sensitivity
handling (see `sensitivity_category` below).

Schema:
    rag.documents -- one row per ingested PDF: filename, which collection,
        upload/processing status, chunk count, and (for "policies" only) a
        hand-set sensitivity category used to gate generation in
        `rag/graph.py`.
    rag.chunks -- one row per chunk: text, position, embedding (VECTOR(384)
        -- fixed to the default embedding model's dimensionality; changing
        `EMBEDDING_MODEL_NAME`/`RAG_EMBEDDING_MODEL_NAME` to a model with a
        different output size requires migrating this column's width too,
        a deliberate, documented limitation rather than a dynamic schema).

Deliberately a separate connection from `DB_CONNECTIONS` (`Settings.databases`)
-- see `Settings.rag_store_connection_string`'s docstring for why chunk/
embedding storage shouldn't share a schema or connection pool with a
configured business database.
"""

from __future__ import annotations

import json
import logging
from dataclasses import dataclass
from functools import cache
from typing import Literal

from sqlalchemy import Engine, create_engine, text

from config.settings import ConfigurationError, Settings, get_settings

logger = logging.getLogger(__name__)

Collection = Literal["documents", "policies"]
DocumentStatus = Literal["processing", "ready", "failed"]

# The three categories signed off on for restricted-content treatment in
# the "policies" collection (see docs/ARCHITECTURE.md's multi-source
# section once it lands, and the sign-off in this project's own history --
# compensation & pay, disciplinary/HR case content, legal/litigation).
# None means "no restricted category" -- the common case for both
# "documents" uploads (never restricted) and most policy uploads.
SensitivityCategory = Literal["compensation", "disciplinary", "legal"] | None

_VALID_SENSITIVITY_CATEGORIES: frozenset[str] = frozenset({"compensation", "disciplinary", "legal"})

# Fixed to all-MiniLM-L6-v2's (and Chroma's DefaultEmbeddingFunction's, which
# is the same model) output size -- see this module's docstring.
EMBEDDING_DIMENSIONS = 384

# A 384-float JSON array is long enough (~7000+ characters) that pyodbc
# binds it as SQL_WLONGVARCHAR (ntext) rather than SQL_WVARCHAR (nvarchar) --
# a driver-level heuristic based on string length, not something this code
# controls per-parameter. SQL Server's VECTOR CAST only accepts a
# varchar/nvarchar source, not ntext ("Explicit conversion from data type
# ntext to vector is not allowed") -- confirmed against the real error, not
# assumed. Casting through NVARCHAR(MAX) first forces the intermediate type
# pyodbc's automatic binding skips, and *that* cast to VECTOR is accepted.
_VECTOR_CAST = f"CAST(CAST(:embedding AS NVARCHAR(MAX)) AS VECTOR({EMBEDDING_DIMENSIONS}))"


class RagStoreNotConfiguredError(ConfigurationError):
    """Raised when document/policy RAG is enabled but `RAG_STORE_CONNECTION_STRING` isn't set.

    A distinct subclass (not just a bare `ConfigurationError`) so callers
    that want to degrade gracefully (e.g. the router's availability check)
    can catch this specifically rather than any configuration problem.
    """


@dataclass(frozen=True)
class DocumentRecord:
    """One ingested PDF, as listed in the "Knowledge Sources" management view."""

    id: str
    filename: str
    collection: Collection
    sensitivity_category: str | None
    upload_date: str
    status: DocumentStatus
    chunk_count: int
    error_message: str | None
    has_pdf_bytes: bool
    # 2026 Phase 3 security review: `uploaded_by` is audit-trail-only (the
    # uploader's `AuthIdentity.subject`) -- this app remains a *shared*
    # knowledge base by design (see docs/AUTHORIZATION.md's "no per-resource
    # ownership" note), so retrieval/download/delete are never scoped to
    # "documents this caller uploaded." `restricted_roles`, unlike
    # `uploaded_by`, IS an access-control field: when set, only a caller
    # holding at least one of these roles may have this document's content
    # summarized into an answer or downloaded -- a more general, per-
    # document mechanism alongside (not replacing) the existing fixed
    # `sensitivity_category` gate, for content that needs restricting but
    # doesn't fit "compensation"/"disciplinary"/"legal".
    uploaded_by: str | None = None
    restricted_roles: tuple[str, ...] | None = None


@dataclass(frozen=True)
class ChunkResult:
    """One retrieved chunk, with enough provenance to cite it in a generated answer."""

    chunk_text: str
    similarity: float
    document_id: str
    filename: str
    chunk_index: int
    page_number: int | None
    sensitivity_category: str | None
    has_pdf_bytes: bool
    restricted_roles: tuple[str, ...] | None = None


def _roles_to_csv(roles: tuple[str, ...] | None) -> str | None:
    """Comma-joins `roles` for storage, or None for "no restriction" --
    mirrors `config.settings.Settings`'s own comma-separated-list-in-a-
    single-column convention (`cors_allowed_origins`, `oidc_algorithms`)."""
    if not roles:
        return None
    return ",".join(roles)


def _parse_roles_csv(value: str | None) -> tuple[str, ...] | None:
    if not value:
        return None
    parsed = tuple(role.strip() for role in value.split(",") if role.strip())
    return parsed or None


def _require_connection_string(settings: Settings) -> str:
    if not settings.rag_store_connection_string:
        raise RagStoreNotConfiguredError(
            "Document/policy RAG is enabled (ENABLE_DOCUMENT_RAG or "
            "ENABLE_POLICY_RAG) but RAG_STORE_CONNECTION_STRING is not set in "
            ".env. Set it to a SQL Server 2025+/Azure SQL connection string -- "
            "see .env.example's RAG section."
        )
    return settings.rag_store_connection_string.get_secret_value()


@cache
def _cached_rag_engine(connection_string: str) -> Engine:
    """Process-wide engine cache, mirroring `db.connection._cached_engine`."""
    return create_engine(connection_string, pool_pre_ping=True, pool_recycle=1800)


def get_rag_engine(settings: Settings | None = None) -> Engine:
    """Returns the (cached, pooled) engine for the RAG store connection.

    Raises:
        RagStoreNotConfiguredError: if `RAG_STORE_CONNECTION_STRING` is unset.
    """
    settings = settings or get_settings()
    connection_string = _require_connection_string(settings)
    return _cached_rag_engine(connection_string)


def ensure_schema(engine: Engine) -> None:
    """Creates the `rag` schema and its two tables if they don't already exist.

    Idempotent (`IF ... IS NULL CREATE ...`) -- safe to call on every
    ingestion/retrieval entry point rather than requiring a separate manual
    migration step, the same "just works on first use" posture
    `db.schema_introspection` and `embeddings.schema_indexer` already have
    for their own storage.

    Also handles the one schema *migration* this module has needed so far:
    an existing `rag.documents` table (created before `pdf_bytes` existed)
    gets the column added via `IF NOT EXISTS (SELECT ... sys.columns) ALTER
    TABLE`, guarded the same idempotent way as the `CREATE TABLE` blocks
    above -- an operator upgrading this codebase never needs a separate
    manual migration step, the next call to `ensure_schema()` (i.e. the
    next ingestion or question) just adds it.
    """
    with engine.begin() as conn:
        conn.execute(text("IF SCHEMA_ID('rag') IS NULL EXEC('CREATE SCHEMA rag')"))
        conn.execute(
            text(
                """
                IF OBJECT_ID('rag.documents') IS NULL
                CREATE TABLE rag.documents (
                    id UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_rag_documents_id DEFAULT NEWID(),
                    filename NVARCHAR(400) NOT NULL,
                    collection NVARCHAR(50) NOT NULL,
                    sensitivity_category NVARCHAR(50) NULL,
                    upload_date DATETIME2 NOT NULL
                        CONSTRAINT DF_rag_documents_upload_date DEFAULT SYSUTCDATETIME(),
                    status NVARCHAR(20) NOT NULL
                        CONSTRAINT DF_rag_documents_status DEFAULT 'processing',
                    chunk_count INT NOT NULL CONSTRAINT DF_rag_documents_chunk_count DEFAULT 0,
                    error_message NVARCHAR(MAX) NULL,
                    source_metadata NVARCHAR(MAX) NULL,
                    pdf_bytes VARBINARY(MAX) NULL,
                    uploaded_by NVARCHAR(200) NULL,
                    restricted_roles NVARCHAR(500) NULL,
                    CONSTRAINT PK_rag_documents PRIMARY KEY (id)
                )
                """
            )
        )
        # Migration for a `rag.documents` table created before `pdf_bytes`
        # existed -- a fresh CREATE TABLE above already includes it, so this
        # is a no-op on a new install and only fires once per pre-existing
        # deployment (see `enable_pdf_download`'s docstring in
        # config/settings.py for what this column is for).
        conn.execute(
            text(
                """
                IF NOT EXISTS (
                    SELECT 1 FROM sys.columns
                    WHERE object_id = OBJECT_ID('rag.documents') AND name = 'pdf_bytes'
                )
                ALTER TABLE rag.documents ADD pdf_bytes VARBINARY(MAX) NULL
                """
            )
        )
        # 2026 Phase 3 security review: same idempotent-migration pattern
        # as pdf_bytes above, for the two new document-access-control
        # columns (see DocumentRecord's docstring for what each is for).
        conn.execute(
            text(
                """
                IF NOT EXISTS (
                    SELECT 1 FROM sys.columns
                    WHERE object_id = OBJECT_ID('rag.documents') AND name = 'uploaded_by'
                )
                ALTER TABLE rag.documents ADD uploaded_by NVARCHAR(200) NULL
                """
            )
        )
        conn.execute(
            text(
                """
                IF NOT EXISTS (
                    SELECT 1 FROM sys.columns
                    WHERE object_id = OBJECT_ID('rag.documents') AND name = 'restricted_roles'
                )
                ALTER TABLE rag.documents ADD restricted_roles NVARCHAR(500) NULL
                """
            )
        )
        conn.execute(
            text(
                f"""
                IF OBJECT_ID('rag.chunks') IS NULL
                CREATE TABLE rag.chunks (
                    id UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_rag_chunks_id DEFAULT NEWID(),
                    document_id UNIQUEIDENTIFIER NOT NULL,
                    chunk_index INT NOT NULL,
                    chunk_text NVARCHAR(MAX) NOT NULL,
                    embedding VECTOR({EMBEDDING_DIMENSIONS}) NOT NULL,
                    page_number INT NULL,
                    metadata NVARCHAR(MAX) NULL,
                    CONSTRAINT PK_rag_chunks PRIMARY KEY (id),
                    CONSTRAINT FK_rag_chunks_document FOREIGN KEY (document_id)
                        REFERENCES rag.documents(id) ON DELETE CASCADE
                )
                """
            )
        )


def insert_document(
    engine: Engine,
    filename: str,
    collection: Collection,
    sensitivity_category: SensitivityCategory = None,
    source_metadata: dict | None = None,
    pdf_bytes: bytes | None = None,
    uploaded_by: str | None = None,
    restricted_roles: tuple[str, ...] | None = None,
) -> str:
    """Inserts a new `rag.documents` row with status "processing" and returns its id.

    Args:
        pdf_bytes: The original uploaded file's raw bytes, or None to store
            nothing (e.g. `Settings.enable_pdf_download` is off). Binds
            directly as `VARBINARY` -- unlike `insert_chunks`' embedding
            column, this needs none of `_VECTOR_CAST`'s ntext-vs-nvarchar
            workaround, since that quirk is specific to casting a long JSON
            string into `VECTOR`.
        uploaded_by: The uploader's `AuthIdentity.subject` -- audit-trail
            only, never used to scope retrieval/download/delete (see
            `DocumentRecord`'s docstring: this app is a shared knowledge
            base by design).
        restricted_roles: If set, only a caller holding at least one of
            these role names may have this document summarized into an
            answer or download it (`rag/graph.py::_generate_node`,
            `api/documents.py::download_document`) -- a more general
            access-control mechanism than the fixed `sensitivity_category`
            enum, for content that needs restricting but doesn't fit one of
            the three reviewed categories. Role names are not validated
            against `agent.authz.ROLE_PERMISSIONS` here -- that mapping is
            deliberately extensible/operator-editable (see that module's
            own docstring), so an unrecognized role name here isn't
            necessarily a mistake; it just means no current caller can see
            this document until a role granting access exists, which is a
            safe (fail-closed, not fail-open) default for a typo.

    Raises:
        ValueError: if `sensitivity_category` isn't one of the reviewed
            categories (or None) -- fails fast rather than silently storing
            an uncategorized value that `rag/graph.py`'s restriction check
            would then never match.
    """
    if (
        sensitivity_category is not None
        and sensitivity_category not in _VALID_SENSITIVITY_CATEGORIES
    ):
        raise ValueError(
            f"sensitivity_category={sensitivity_category!r} is not one of "
            f"{sorted(_VALID_SENSITIVITY_CATEGORIES)} (or None)."
        )
    with engine.begin() as conn:
        result = conn.execute(
            text(
                """
                INSERT INTO rag.documents
                    (filename, collection, sensitivity_category, source_metadata, pdf_bytes,
                     uploaded_by, restricted_roles)
                OUTPUT inserted.id
                VALUES (:filename, :collection, :sensitivity_category, :source_metadata, :pdf_bytes,
                        :uploaded_by, :restricted_roles)
                """
            ),
            {
                "filename": filename,
                "collection": collection,
                "sensitivity_category": sensitivity_category,
                "source_metadata": json.dumps(source_metadata) if source_metadata else None,
                "pdf_bytes": pdf_bytes,
                "uploaded_by": uploaded_by,
                "restricted_roles": _roles_to_csv(restricted_roles),
            },
        )
        return str(result.scalar_one())


def update_document_status(
    engine: Engine,
    document_id: str,
    status: DocumentStatus,
    chunk_count: int | None = None,
    error_message: str | None = None,
) -> None:
    """Updates a document's status after ingestion succeeds or fails."""
    with engine.begin() as conn:
        conn.execute(
            text(
                """
                UPDATE rag.documents
                SET status = :status,
                    chunk_count = COALESCE(:chunk_count, chunk_count),
                    error_message = :error_message
                WHERE id = :document_id
                """
            ),
            {
                "status": status,
                "chunk_count": chunk_count,
                "error_message": error_message,
                "document_id": document_id,
            },
        )


def insert_chunks(
    engine: Engine,
    document_id: str,
    chunks: list[tuple[str, int, list[float], int | None]],
) -> None:
    """Bulk-inserts chunks for one document.

    Args:
        chunks: `(chunk_text, chunk_index, embedding, page_number)` tuples,
            already embedded (see `rag/ingestion.py`) -- this function is
            pure storage, it never calls an embedding model itself.
    """
    with engine.begin() as conn:
        for chunk_text_value, chunk_index, embedding, page_number in chunks:
            conn.execute(
                # Bandit's SQL-construction heuristic (B608) false-positives
                # here -- `_VECTOR_CAST` is a fixed module-level constant
                # (see its own docstring: EMBEDDING_DIMENSIONS baked in, not
                # user input), every real value is bound as a parameter
                # (:document_id etc.), never interpolated. Single-line
                # f-strings (not one multi-line triple-quoted string) purely
                # so the `# nosec` marker below can sit outside the string
                # literal itself, rather than inside it (a multi-line
                # f-string's `# nosec` would have become literal SQL text).
                text(
                    "INSERT INTO rag.chunks (document_id, chunk_index, chunk_text, embedding, page_number) "  # nosec B608
                    f"VALUES (:document_id, :chunk_index, :chunk_text, {_VECTOR_CAST}, :page_number)"
                ),
                {
                    "document_id": document_id,
                    "chunk_index": chunk_index,
                    "chunk_text": chunk_text_value,
                    "embedding": json.dumps(embedding),
                    "page_number": page_number,
                },
            )


def list_documents(engine: Engine, collection: Collection | None = None) -> list[DocumentRecord]:
    """Lists ingested documents, newest first -- the management view's data source.

    Deliberately projects `has_pdf_bytes` (a cheap NULL check) rather than
    `pdf_bytes` itself -- a listing query must never pull every document's
    full blob into memory just to render a table; the actual bytes are only
    ever fetched on demand, by `get_document_bytes`, when a user clicks a
    download button for one specific document.
    """
    query = """
        SELECT id, filename, collection, sensitivity_category, upload_date,
               status, chunk_count, error_message,
               CASE WHEN pdf_bytes IS NOT NULL THEN 1 ELSE 0 END AS has_pdf_bytes,
               uploaded_by, restricted_roles
        FROM rag.documents
    """
    params: dict[str, str] = {}
    if collection is not None:
        query += " WHERE collection = :collection"
        params["collection"] = collection
    query += " ORDER BY upload_date DESC"

    with engine.connect() as conn:
        rows = conn.execute(text(query), params).fetchall()
    return [
        DocumentRecord(
            id=str(row.id),
            filename=row.filename,
            collection=row.collection,
            sensitivity_category=row.sensitivity_category,
            upload_date=str(row.upload_date),
            status=row.status,
            chunk_count=row.chunk_count,
            error_message=row.error_message,
            has_pdf_bytes=bool(row.has_pdf_bytes),
            uploaded_by=row.uploaded_by,
            restricted_roles=_parse_roles_csv(row.restricted_roles),
        )
        for row in rows
    ]


def get_document_sensitivity(engine: Engine, document_id: str) -> str | None:
    """Fetches one document's `sensitivity_category` without pulling its
    (potentially large) `pdf_bytes` blob -- 2026 Phase 2 security review:
    `api/documents.py`'s download route uses this to decide whether the
    caller needs `agent.authz.Permission.DOCUMENTS_READ_SENSITIVE`,
    closing the gap where a sensitivity-tagged document's raw bytes were
    downloadable through this route with no access check beyond the
    general document-management permission (the chat-answer sensitivity
    gate in `rag/graph.py` was always a separate, narrower control -- see
    that module's docstring).

    Returns `None` both for a document ID that doesn't exist and for one
    that exists but isn't sensitivity-tagged -- callers that need to tell
    these apart (this one doesn't: it only ever calls this after already
    confirming the document exists via `get_document_bytes`) should check
    existence separately first.
    """
    with engine.connect() as conn:
        row = conn.execute(
            text("SELECT sensitivity_category FROM rag.documents WHERE id = :document_id"),
            {"document_id": document_id},
        ).fetchone()
    if row is None:
        return None
    return row.sensitivity_category


def get_document_restricted_roles(engine: Engine, document_id: str) -> tuple[str, ...] | None:
    """Fetches one document's `restricted_roles` -- the same purpose as
    `get_document_sensitivity` above, for the more general role-restriction
    mechanism (`DocumentRecord`'s docstring). `api/documents.py`'s download
    route uses this alongside `get_document_sensitivity` so both access-
    control fields gate a raw-bytes download the same way they already gate
    a chat-answer summary (`rag/graph.py::_generate_node`)."""
    with engine.connect() as conn:
        row = conn.execute(
            text("SELECT restricted_roles FROM rag.documents WHERE id = :document_id"),
            {"document_id": document_id},
        ).fetchone()
    if row is None:
        return None
    return _parse_roles_csv(row.restricted_roles)


def get_document_bytes(engine: Engine, document_id: str) -> bytes | None:
    """Fetches one document's original PDF bytes, or None if never stored.

    The only place `pdf_bytes` is ever read in full -- called on demand
    right when a download button needs data (`api/documents.py`'s download
    route, the dashboard's Knowledge Sources page), never
    as part of a listing/search query.
    """
    with engine.connect() as conn:
        row = conn.execute(
            text("SELECT pdf_bytes FROM rag.documents WHERE id = :document_id"),
            {"document_id": document_id},
        ).fetchone()
    if row is None or row.pdf_bytes is None:
        return None
    return bytes(row.pdf_bytes)


def delete_document(engine: Engine, document_id: str) -> None:
    """Deletes a document and its chunks (ON DELETE CASCADE handles the chunks)."""
    with engine.begin() as conn:
        conn.execute(
            text("DELETE FROM rag.documents WHERE id = :document_id"), {"document_id": document_id}
        )


def similarity_search(
    engine: Engine,
    collection: Collection,
    query_embedding: list[float],
    top_k: int,
) -> list[ChunkResult]:
    """Top-k chunks in `collection` by cosine similarity to `query_embedding`.

    Only chunks belonging to a `status = 'ready'` document are searched -- a
    still-processing or failed ingestion never contributes a half-indexed
    chunk to a live question.

    `VECTOR_DISTANCE('cosine', ...)` returns a *distance* (0 = identical);
    `similarity = 1 - distance` mirrors `embeddings/retriever.py`'s own
    cosine-distance-to-similarity convention for schema retrieval, so a
    "higher is better" score means the same thing in both retrieval paths.
    """
    with engine.connect() as conn:
        rows = conn.execute(
            # Bandit's SQL-construction heuristic (B608) false-positives
            # here -- same reasoning as insert_chunks above: `_VECTOR_CAST`
            # is a fixed module-level constant, every real value is bound
            # as a parameter (:top_k/:collection/:embedding), never
            # interpolated. Single-line concatenated string literals (not
            # one multi-line triple-quoted f-string) so `# nosec` can sit
            # outside the string itself.
            text(
                "SELECT TOP (:top_k) "  # nosec B608
                "c.chunk_text, c.chunk_index, c.page_number, "
                "d.id AS document_id, d.filename, d.sensitivity_category, "
                "CASE WHEN d.pdf_bytes IS NOT NULL THEN 1 ELSE 0 END AS has_pdf_bytes, "
                "d.restricted_roles, "
                f"VECTOR_DISTANCE('cosine', c.embedding, {_VECTOR_CAST}) AS distance "
                "FROM rag.chunks c "
                "JOIN rag.documents d ON d.id = c.document_id "
                "WHERE d.collection = :collection AND d.status = 'ready' "
                "ORDER BY distance ASC"
            ),
            {
                "top_k": top_k,
                "collection": collection,
                "embedding": json.dumps(query_embedding),
            },
        ).fetchall()
    return [
        ChunkResult(
            chunk_text=row.chunk_text,
            similarity=1.0 - float(row.distance),
            document_id=str(row.document_id),
            filename=row.filename,
            chunk_index=row.chunk_index,
            page_number=row.page_number,
            sensitivity_category=row.sensitivity_category,
            has_pdf_bytes=bool(row.has_pdf_bytes),
            restricted_roles=_parse_roles_csv(row.restricted_roles),
        )
        for row in rows
    ]
