TOOL_NAME = "resolve_ordinal"
TOOL_DESCRIPTION = (
    "Convert an ordinal reference (Dutch or English) into a 0-based list index. "
    "Handles number words ('eerste', 'tweede', 'third'), digits ('nr 3', 'nummer 5'), "
    "and position words ('laatste', 'last', 'vorige', 'previous'). "
    "Use this to pick an item from a list of emails, calendar events, or search results."
)
TOOL_ARGS = '{"expression": {"type": "string", "description": "The ordinal expression, e.g. eerste, nr 3, de derde, laatste"}, "list_length": {"type": "integer", "default": 0, "description": "Total items in the list, needed for laatste/last"}}'

import re
from tools._std import tool_ok, tool_error

_WORD_TO_INDEX = {
    "eerste": 0, "first": 0, "1e": 0, "1ste": 0,
    "tweede": 1, "second": 1, "2e": 1, "2de": 1,
    "derde": 2, "third": 2, "3e": 2, "3de": 2,
    "vierde": 3, "fourth": 3, "4e": 3, "4de": 3,
    "vijfde": 4, "fifth": 4, "5e": 4, "5de": 4,
    "zesde": 5, "sixth": 5, "6e": 5, "6de": 5,
    "zevende": 6, "seventh": 6, "7e": 6, "7de": 6,
    "achtste": 7, "eighth": 7, "8e": 7, "8ste": 7,
    "negende": 8, "ninth": 8, "9e": 8, "9de": 8,
    "tiende": 9, "tenth": 9, "10e": 9, "10de": 9,
}

_NUMBER_WORDS = {
    "een": 1, "one": 1,
    "twee": 2, "two": 2,
    "drie": 3, "three": 3,
    "vier": 4, "four": 4,
    "vijf": 5, "five": 5,
    "zes": 6, "six": 6,
    "zeven": 7, "seven": 7,
    "acht": 8, "eight": 8,
    "negen": 9, "nine": 9,
    "tien": 10, "ten": 10,
}


def run(args: dict) -> str:
    expr = str(args.get("expression") or "").strip().lower()
    list_length = int(args.get("list_length") or 0)
    if not expr:
        return tool_error("No expression provided")

    # --- "laatste" / "last" / "vorige" / "previous" ---
    if re.search(r"\b(laatste|last|vorige|previous)\b", expr):
        if list_length > 0:
            return tool_ok({"index": list_length - 1, "position": "last"})
        return tool_ok({"index": -1, "position": "last"})

    # --- "op een na laatste" / "second to last" / "voorlaatste" ---
    if re.search(r"\b(voorlaatste|op een na laatste|second to last|penultimate)\b", expr):
        if list_length > 1:
            return tool_ok({"index": list_length - 2, "position": "second_to_last"})
        return tool_ok({"index": -2, "position": "second_to_last"})

    # --- "nummer N" / "nr N" / "number N" / "#N" ---
    m = re.search(r"\b(?:nummer|nr\.?|number|#)\s*(\d{1,3})\b", expr)
    if m:
        n = int(m.group(1))
        return tool_ok({"index": max(0, n - 1), "position": n})

    # --- Bare digit: "3", "email 5" ---
    m = re.search(r"\b(\d{1,3})\b", expr)
    if m:
        n = int(m.group(1))
        if 1 <= n <= 100:
            return tool_ok({"index": max(0, n - 1), "position": n})

    # --- Ordinal words: "eerste", "third", "3e" ---
    for token in expr.split():
        token = token.strip(",.;:!?\"'()")
        if token in _WORD_TO_INDEX:
            return tool_ok({"index": _WORD_TO_INDEX[token], "position": _WORD_TO_INDEX[token] + 1})

    # --- Number words: "twee" → index 1 ---
    for token in expr.split():
        token = token.strip(",.;:!?\"'()")
        if token in _NUMBER_WORDS:
            n = _NUMBER_WORDS[token]
            return tool_ok({"index": max(0, n - 1), "position": n})

    return tool_error(f"Could not resolve ordinal: '{args.get('expression', '')}'")
