from time import time
from typing import Optional
from ..logger import log
from .coreagent import MultiTenantSalesAgent

# Cache stores a tuple of (agent_instance, timestamp)
_agent_cache: dict[str, tuple[MultiTenantSalesAgent, float]] = {}

# TTL in seconds
AGENT_TTL = 3600  # e.g., 1 hour


def get_sales_agent(chat_id: str, store_id: Optional[str]) -> MultiTenantSalesAgent:
    """Cached sales agent factory (per chat session) with TTL."""
    current_time = time()

    if chat_id in _agent_cache:
        agent, timestamp = _agent_cache[chat_id]
        if current_time - timestamp < AGENT_TTL:
            log.info(
                "Reusing %s for chat_id=%s store_id=%s",
                agent.__class__.__name__,
                chat_id,
                store_id,
            )
            return agent
        log.info(
            "Expired %s for chat_id=%s store_id=%s",
            agent.__class__.__name__,
            chat_id,
            store_id,
        )

    agent = MultiTenantSalesAgent(chat_id, store_id)
    _agent_cache[chat_id] = (agent, current_time)
    log.info(
        "Created %s for chat_id=%s store_id=%s",
        agent.__class__.__name__,
        chat_id,
        store_id,
    )
    return agent
