"""Text formatting utility tools."""

import re

from pydantic_ai.toolsets import FunctionToolset

formatting_toolset: FunctionToolset[None] = FunctionToolset()


@formatting_toolset.tool
def format_as_bullet_list(
    items: list[str],
    style: str = "dash",
) -> str:
    """Format items as a bullet list.

    Args:
        items: List of items to format.
        style: Bullet style - 'dash', 'asterisk', or 'number'.
    """
    if not items:
        return "No items to format."

    if style == "dash":
        return "\n".join(f"- {item}" for item in items)
    elif style == "asterisk":
        return "\n".join(f"* {item}" for item in items)
    elif style == "number":
        return "\n".join(f"{i}. {item}" for i, item in enumerate(items, 1))
    else:
        return f"Unknown style: {style}. Use 'dash', 'asterisk', or 'number'."


@formatting_toolset.tool
def truncate_text(
    text: str,
    max_length: int = 200,
    suffix: str = "...",
) -> str:
    """Truncate text to a maximum length.

    Args:
        text: Text to truncate.
        max_length: Maximum length (default 200).
        suffix: Suffix to add when truncated (default '...').
    """
    if len(text) <= max_length:
        return text

    return text[: max_length - len(suffix)] + suffix


@formatting_toolset.tool
def extract_keywords(
    text: str,
    max_keywords: int = 10,
) -> str:
    """Extract keywords from text.

    Args:
        text: Text to extract keywords from.
        max_keywords: Maximum number of keywords to return.
    """
    # Simple keyword extraction (in production, use NLP library)
    # Remove common stop words
    stop_words = {
        "the",
        "a",
        "an",
        "and",
        "or",
        "but",
        "in",
        "on",
        "at",
        "to",
        "for",
        "of",
        "with",
        "by",
        "from",
        "is",
        "are",
        "was",
        "were",
        "be",
        "been",
        "being",
        "have",
        "has",
        "had",
        "do",
        "does",
        "did",
        "will",
        "would",
        "could",
        "should",
        "may",
        "might",
        "can",
        "this",
        "that",
        "these",
        "those",
        "it",
        "its",
    }

    # Extract words
    words = re.findall(r"\b[a-zA-Z]{3,}\b", text.lower())

    # Count frequencies (excluding stop words)
    freq: dict[str, int] = {}
    for word in words:
        if word not in stop_words:
            freq[word] = freq.get(word, 0) + 1

    # Sort by frequency
    sorted_words = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    keywords = [word for word, _ in sorted_words[:max_keywords]]

    return f"Keywords: {', '.join(keywords)}"


@formatting_toolset.tool
def format_number(
    value: float,
    style: str = "standard",
    decimals: int = 2,
) -> str:
    """Format a number in various styles.

    Args:
        value: Number to format.
        style: Format style - 'standard', 'currency', 'percentage', 'compact'.
        decimals: Number of decimal places.
    """
    if style == "standard":
        return f"{value:,.{decimals}f}"
    elif style == "currency":
        return f"${value:,.{decimals}f}"
    elif style == "percentage":
        return f"{value:.{decimals}f}%"
    elif style == "compact":
        if abs(value) >= 1_000_000_000:
            return f"{value / 1_000_000_000:.{decimals}f}B"
        elif abs(value) >= 1_000_000:
            return f"{value / 1_000_000:.{decimals}f}M"
        elif abs(value) >= 1_000:
            return f"{value / 1_000:.{decimals}f}K"
        else:
            return f"{value:.{decimals}f}"
    else:
        return f"Unknown style: {style}"


@formatting_toolset.tool
def clean_text(
    text: str,
    remove_extra_whitespace: bool = True,
    remove_urls: bool = False,
    lowercase: bool = False,
) -> str:
    """Clean and normalize text.

    Args:
        text: Text to clean.
        remove_extra_whitespace: Collapse multiple spaces into one.
        remove_urls: Remove URLs from text.
        lowercase: Convert to lowercase.
    """
    result = text

    if remove_urls:
        result = re.sub(r"https?://\S+", "", result, flags=re.IGNORECASE)

    if remove_extra_whitespace:
        result = re.sub(r"\s+", " ", result).strip()

    if lowercase:
        result = result.lower()

    return result
