from __future__ import annotations

from typing import Any


def estimate_context_for_thread(thread_id: str) -> dict[str, Any]:
    from chat_storage import get_messages
    from context_summarizer import build_merged_history_for_main_agent
    from agent_research import estimate_tokens
    from agent_loop_config import get_llm_context_length
    from core import get_config

    raw_messages = get_messages(thread_id, include_row_id=True) or []
    raw_messages = [m for m in raw_messages if isinstance(m, dict) and m.get("role") in ("user", "assistant")]

    messages = build_merged_history_for_main_agent(thread_id, raw_messages)

    est = int(estimate_tokens(messages))
    limit = int(get_llm_context_length())
    cfg = get_config() or {}
    trigger_frac = float(((cfg.get("summarization") or {}).get("trigger_fraction", 0.6)) or 0.6)
    trigger_tokens = int(limit * trigger_frac)
    return {
        "estimated_tokens": est,
        "context_limit": limit,
        "messages_count": len(messages),
        "summarization_trigger_tokens": trigger_tokens,
    }
