TOOL_NAME = "clean_entity"
TOOL_DESCRIPTION = (
    "Clean a raw entity/name extracted from user text by stripping filler words, "
    "articles, provider names, time expressions, and verbal noise. "
    "Use this to normalize a sender name, subject, or search query before passing it to an API. "
    "Example: 'de emails van Jan uit gmail gisteren' → 'Jan'"
)
TOOL_ARGS = '{"text": {"type": "string", "description": "The raw entity text to clean"}}'

import re
from tools._std import tool_ok, tool_error

_MONTH_NAMES = (
    "januari|february|februari|march|maart|april|mei|may|juni|june|juli|july|"
    "augustus|august|september|oktober|october|november|december|"
    "jan|feb|mrt|apr|jun|jul|aug|sep|okt|nov|dec|mar|oct"
)


def run(args: dict) -> str:
    text = str(args.get("text") or "").strip()
    if not text:
        return tool_error("No text provided")

    value = text.strip(" \t\r\n.,;:!?\"'")
    # Strip leading articles
    value = re.sub(r"^(?:de|het|een|the|a|an)\s+", "", value, flags=re.IGNORECASE)
    # Strip provider references
    value = re.sub(
        r"\s+(?:in|via|uit|from|op)\s+(?:gmail|google mail|outlook|mijn inbox|my inbox)\b.*$",
        "", value, flags=re.IGNORECASE,
    )
    # Strip time expressions at end
    value = re.sub(
        rf"\s+(?:vandaag|today|gisteren|yesterday|morgen|tomorrow|"
        rf"deze week|this week|vorige week|last week|"
        rf"deze maand|this month|vorige maand|last month|"
        rf"in\s+(?:{_MONTH_NAMES})(?:\s+\d{{4}})?)\b.*$",
        "", value, flags=re.IGNORECASE,
    )
    # Strip Dutch verbal noise
    value = re.sub(r"\s+(?:heb ik|have i|ik heb|die ik|that i)\b.*$", "", value, flags=re.IGNORECASE)
    value = re.sub(r"\s+(?:bedoel ik|please|graag|alsjeblieft)$", "", value, flags=re.IGNORECASE)
    value = re.sub(
        r"\s+(?:gekregen|ontvangen|binnengekregen|gehad|received|gotten|had|gestuurd|sent)\s*$",
        "", value, flags=re.IGNORECASE,
    )
    # Strip prepositions left at start
    value = re.sub(r"^(?:van|from|naar|to|over|about|met|with)\s+", "", value, flags=re.IGNORECASE)
    # Collapse whitespace
    value = re.sub(r"\s+", " ", value).strip(" \t\r\n.,;:!?\"'")

    if not value:
        return tool_error("Entity cleaned to empty string")
    return tool_ok({"cleaned": value, "original": text})
