Newer
Older
gnexus-book / server / app / storage / db_repositories.py
from __future__ import annotations

from typing import Any

import yaml
from sqlalchemy import and_, func, select
from sqlalchemy.orm import Session

from ..docs_repository import RepositoryError
from ..inventory import InventoryError
from .db import Database
from .models import DocVersion, Document, InventoryItem, InventoryType


def _latest_doc_versions():
    return (
        select(
            DocVersion.document_id.label("document_id"),
            func.max(DocVersion.version_no).label("version_no"),
        )
        .group_by(DocVersion.document_id)
        .subquery()
    )


def latest_doc_rows(session: Session):
    latest = _latest_doc_versions()
    return (
        select(Document, DocVersion)
        .join(latest, latest.c.document_id == Document.id)
        .join(
            DocVersion,
            and_(
                DocVersion.document_id == Document.id,
                DocVersion.version_no == latest.c.version_no,
            ),
        )
        .where(Document.deleted_at.is_(None))
        .order_by(Document.slug)
    )


class PostgresDocsRepository:
    def __init__(self, database: Database) -> None:
        self.database = database

    def list_docs(self) -> list[dict[str, object]]:
        with self.database.session() as session:
            rows = sorted(
                session.execute(latest_doc_rows(session)).all(),
                key=lambda row: row[0].slug,
            )
            return [
                {
                    "path": document.slug,
                    "title": document.title,
                    "frontmatter": dict(version.frontmatter or {}),
                }
                for document, version in rows
            ]

    def read_doc(self, path: str) -> dict[str, object]:
        with self.database.session() as session:
            row = session.execute(
                latest_doc_rows(session)
                .where(Document.slug == path)
                .limit(1)
            ).first()
            if row is None:
                raise RepositoryError("Document not found")
            document, version = row
            return {
                "path": document.slug,
                "frontmatter": dict(version.frontmatter or {}),
                "body": version.body,
                "raw": version.raw,
            }

    def search(self, query: str) -> list[dict[str, object]]:
        normalized = query.strip().lower()
        if not normalized:
            return []

        results: list[dict[str, object]] = []
        with self.database.session() as session:
            rows = sorted(
                session.execute(latest_doc_rows(session)).all(),
                key=lambda row: row[0].slug,
            )
            for document, version in rows:
                matches = []
                for index, line in enumerate(version.raw.splitlines(), start=1):
                    if normalized in line.lower():
                        matches.append({"line": index, "text": line.strip()})
                    if len(matches) >= 5:
                        break
                if matches:
                    results.append(
                        {
                            "path": document.slug,
                            "title": document.title,
                            "matches": matches,
                        }
                    )
        return results


class PostgresInventoryRepository:
    def __init__(self, database: Database) -> None:
        self.database = database

    def list_types(self) -> list[str]:
        with self.database.session() as session:
            return list(session.scalars(select(InventoryType.name).order_by(InventoryType.name)))

    def read_raw(self, inventory_type: str) -> str:
        data = self.read_parsed(inventory_type)
        return "---\n" + yaml.safe_dump(data, sort_keys=False, allow_unicode=True)

    def read_parsed(self, inventory_type: str) -> Any:
        self._require_type(inventory_type)
        with self.database.session() as session:
            items = session.scalars(
                select(InventoryItem)
                .where(
                    InventoryItem.type == inventory_type,
                    InventoryItem.deleted_at.is_(None),
                )
                .order_by(InventoryItem.position, InventoryItem.item_id)
            ).all()
            return [dict(item.data or {}) for item in items]

    def read_item(self, inventory_type: str, item_id: str) -> dict[str, Any]:
        self._require_type(inventory_type)
        with self.database.session() as session:
            item = session.scalars(
                select(InventoryItem)
                .where(
                    InventoryItem.type == inventory_type,
                    InventoryItem.item_id == item_id,
                    InventoryItem.deleted_at.is_(None),
                )
                .limit(1)
            ).first()
            if item is None:
                raise InventoryError("Inventory item not found")
            return dict(item.data or {})

    def _require_type(self, inventory_type: str) -> None:
        if "/" in inventory_type or "\\" in inventory_type or inventory_type.startswith("."):
            raise InventoryError("Invalid inventory type")
        with self.database.session() as session:
            exists = session.scalar(
                select(InventoryType.name).where(InventoryType.name == inventory_type)
            )
        if exists is None:
            raise InventoryError("Inventory type not found")