from langchain_core.tools import tool

from app.db.database import SessionLocal
from app.db.fts import search_faqs


def make_faq_tool(tenant_id: str):
    @tool
    def search_faq(query: str) -> str:
        """Search this business's FAQ knowledge base for information relevant to the user's question
        (policies, hours, pricing basics, processes, contact info, etc).
        Always try this tool for general/informational questions before answering.
        Returns 'NO_MATCH' if nothing relevant was found."""
        db = SessionLocal()
        try:
            results = search_faqs(db, tenant_id, query, limit=3)
        finally:
            db.close()
        if not results:
            return "NO_MATCH"
        return "\n\n".join(f"Q: {r['question']}\nA: {r['answer']}" for r in results)

    return search_faq
