import json
import logging
import os
import time
from collections.abc import Callable
from typing import Any, cast

from common.ui import console


logger = logging.getLogger(__name__)

def count_tokens(content: str | list[dict[str, str]] | dict[str, Any]) -> int:
    """Count tokens in content using character-based estimation (1 token per 3.4 characters)."""
    text = extract_text_content(content)
    if not text:
        return 0

    # Use simple character-based estimation: 1 token per 3.4 characters (rounded)
    result = round(len(text) / 3.4)
    # Ensure at least 1 token for non-empty text
    return result if result > 0 else 1


def extract_text_content(content: str | list[dict[str, str]] | dict[str, Any]) -> str:
    """Extract text content from various input formats."""
    if isinstance(content, str):
        return content
    elif isinstance(content, list):
        return "\n".join(msg["content"] for msg in content if isinstance(msg, dict) and "content" in msg)
    elif isinstance(content, dict) and "content" in content:
        return cast(str, content["content"])
    return ""