"""
Concept Search - Search concepts and fields using text matching.

Uses Postgres tsvector/ILIKE for text search when backed by a database.
"""

from __future__ import annotations

from typing import Any

from pycharter.wiki.shared.errors import GraphError


class ConceptSearch:
    """
    Search for concepts and fields in the knowledge graph.

    Args:
        session: SQLAlchemy session
    """

    def __init__(self, session=None):
        self._session = session

    def _require_session(self):
        if self._session is None:
            raise GraphError("No database session configured")

    def search_concepts(self, query: str, limit: int = 20) -> list[dict[str, Any]]:
        """
        Search concepts by name or description.

        Args:
            query: Search query string
            limit: Max results

        Returns:
            List of matching concept dicts
        """
        self._require_session()

        from sqlalchemy import text

        sql = text("""
            SELECT id, name, description, tier
            FROM pycharter.concepts
            WHERE name ILIKE :pattern OR description ILIKE :pattern
            ORDER BY name
            LIMIT :limit
        """)

        pattern = f"%{query}%"
        result = self._session.execute(sql, {"pattern": pattern, "limit": limit})
        return [
            {
                "id": str(row.id),
                "name": row.name,
                "description": row.description,
                "tier": row.tier,
            }
            for row in result
        ]

    def search_fields(
        self,
        query: str,
        contract_id: str | None = None,
        limit: int = 20,
    ) -> list[dict[str, Any]]:
        """
        Search fields by name or business definition.

        Args:
            query: Search query string
            contract_id: Optional contract filter
            limit: Max results

        Returns:
            List of matching field dicts
        """
        self._require_session()

        from sqlalchemy import text

        if contract_id:
            sql = text("""
                SELECT id, contract_id, name, data_type, business_definition
                FROM pycharter.fields
                WHERE (name ILIKE :pattern OR business_definition ILIKE :pattern)
                  AND contract_id = :contract_id
                ORDER BY name
                LIMIT :limit
            """)
            params = {
                "pattern": f"%{query}%",
                "contract_id": contract_id,
                "limit": limit,
            }
        else:
            sql = text("""
                SELECT id, contract_id, name, data_type, business_definition
                FROM pycharter.fields
                WHERE name ILIKE :pattern OR business_definition ILIKE :pattern
                ORDER BY name
                LIMIT :limit
            """)
            params = {"pattern": f"%{query}%", "limit": limit}

        result = self._session.execute(sql, params)
        return [
            {
                "id": str(row.id),
                "contract_id": row.contract_id,
                "name": row.name,
                "data_type": row.data_type,
                "business_definition": row.business_definition,
            }
            for row in result
        ]
