"""KnowledgeBase repository (tenant-scoped)."""

from __future__ import annotations

import uuid

from sqlalchemy import select
from sqlalchemy.orm import Session

from legate.db.models.knowledge_base import KnowledgeBase


def create(
    db: Session,
    *,
    workspace_id: uuid.UUID,
    name: str,
    description: str = "",
    embedding_provider: str = "",
    embedding_model: str = "",
    created_by: uuid.UUID | None = None,
) -> KnowledgeBase:
    kb = KnowledgeBase(
        workspace_id=workspace_id,
        name=name,
        description=description,
        embedding_provider=embedding_provider,
        embedding_model=embedding_model,
        vector_collection="",  # set below once the id exists
        created_by=created_by,
    )
    db.add(kb)
    db.flush()
    kb.vector_collection = f"ws_{workspace_id.hex}_kb_{kb.id.hex}"
    db.flush()
    return kb


def get(db: Session, *, workspace_id: uuid.UUID, kb_id: uuid.UUID) -> KnowledgeBase | None:
    return db.scalars(
        select(KnowledgeBase).where(
            KnowledgeBase.id == kb_id, KnowledgeBase.workspace_id == workspace_id
        )
    ).first()


def list_for_workspace(db: Session, *, workspace_id: uuid.UUID) -> list[KnowledgeBase]:
    return list(
        db.scalars(
            select(KnowledgeBase)
            .where(KnowledgeBase.workspace_id == workspace_id)
            .order_by(KnowledgeBase.created_at.asc())
        ).all()
    )


def delete(db: Session, kb: KnowledgeBase) -> None:
    db.delete(kb)
    db.flush()
