from utils.spire_word_util import SpireWordDoc
from utils.spire_pdf_util import SpirePdfDoc
from utils.doc_util import DocBase
from functools import lru_cache
from typing import Optional, Tuple
from core.memory import MemoryStore
from core.config import pdf_support_formats

MAX_CACHE = 128


def _normalize_file_ext(file_ext: str) -> str:
    if not file_ext:
        raise ValueError("file_ext is required")
    ext = file_ext.strip().lower()
    if not ext.startswith("."):
        ext = f".{ext}"
    return ext


@lru_cache(maxsize=MAX_CACHE)
def get_cached_doc_tool(conversation_id: str, file_ext: str) -> Tuple[DocBase, str]:
    ext = _normalize_file_ext(file_ext)
    if ext in pdf_support_formats:
        return SpirePdfDoc(), ext
    return SpireWordDoc(), ext


@lru_cache(maxsize=MAX_CACHE)
def get_cached_memory(conversation_id: str) -> MemoryStore:
    return MemoryStore(f"memory_store_{conversation_id}.json")
