# #region TokenEstimator [C:2] [TYPE Class] [SEMANTICS tokens, cost, estimation]
# @BRIEF Estimate token counts and costs for LLM translation operations.
# @RATIONALE Token estimation uses a heuristic (chars/token ratio) since exact tokenization depends on the LLM model.
# @REJECTED Using an external tokenizer library would introduce a heavy dependency for estimation only.

class TokenEstimator:
    """Estimate token counts and costs for LLM operations."""

    CHARS_PER_TOKEN_ESTIMATE: float = 2.2
    OUTPUT_TOKENS_PER_ROW_ESTIMATE: int = 120
    MULTI_LANG_FACTOR: float = 1.2
    TOKEN_COST_PER_1K: float = 0.002
    COST_WARNING_THRESHOLD: int = 30

    # region estimate_prompt_tokens [TYPE Function]
    # @PURPOSE: Estimate token count for a prompt string.
    @staticmethod
    def estimate_prompt_tokens(prompt: str) -> int:
        if not prompt:
            return 0
        return max(1, int(len(prompt) / TokenEstimator.CHARS_PER_TOKEN_ESTIMATE))
    # endregion estimate_prompt_tokens

    # region estimate_output_tokens [TYPE Function]
    # @PURPOSE: Estimate output token count for translating N rows across N languages.
    @staticmethod
    def estimate_output_tokens(row_count: int, num_languages: int = 1) -> int:
        return int(row_count * num_languages * TokenEstimator.OUTPUT_TOKENS_PER_ROW_ESTIMATE * TokenEstimator.MULTI_LANG_FACTOR)
    # endregion estimate_output_tokens

    # region estimate_cost [TYPE Function]
    # @PURPOSE: Estimate cost for a given number of tokens.
    @staticmethod
    def estimate_cost(total_tokens: int, cost_per_1k: float | None = None) -> float:
        rate = cost_per_1k if cost_per_1k is not None else TokenEstimator.TOKEN_COST_PER_1K
        return round((total_tokens / 1000) * rate, 6)
    # endregion estimate_cost

    # region check_cost_warning [TYPE Function]
    # @PURPOSE: Generate cost warning for large previews.
    @staticmethod
    def check_cost_warning(sample_size: int, num_languages: int, estimated_tokens: int, estimated_cost: float) -> str | None:
        if sample_size > TokenEstimator.COST_WARNING_THRESHOLD:
            return (
                f"Large preview — estimated {estimated_tokens} tokens, ~${estimated_cost:.4f} cost "
                f"(across {num_languages} languages)"
            )
        return None
    # endregion check_cost_warning

# #endregion TokenEstimator
