"""Generic article-reading LLM tool.

The ``read_article`` tool fetches any URL and returns its main body text via
trafilatura. URL-generic — not coupled to any feed system.
"""
from __future__ import annotations

from fabledassistant.services.article_fetcher import fetch_article_text
from fabledassistant.services.tools._registry import tool


@tool(
    name="read_article",
    description=(
        "Fetch the main body text of an article at a URL. Use when the user asks "
        "to read, summarize, or discuss a specific article they've linked. "
        "Returns the cleaned article text or an empty result if extraction fails."
    ),
    parameters={
        "url": {
            "type": "string",
            "description": "The article URL to fetch.",
        },
    },
    required=["url"],
    read_only=True,
)
async def read_article_tool(*, user_id, arguments, **_ctx):
    url = (arguments.get("url") or "").strip()
    if not url:
        return {"success": False, "error": "url is required"}
    content = await fetch_article_text(url)
    if not content:
        return {"success": True, "type": "article", "data": {"url": url, "content": None, "note": "no content extracted"}}
    return {"success": True, "type": "article", "data": {"url": url, "content": content[:6000]}}
