import logging
import datetime
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from pangramia.yt.tokens_ops import YTTokenOpService

logger = logging.getLogger(__name__)

def get_thrift_client(host: str, port: int, timeout_ms: int = 30000):
    """
    Helper function to create and connect a Thrift client.
    Returns a tuple of (client, transport).
    """
    logger.info(f"Connecting to Thrift server at {host}:{port}...")
    transport = TSocket.TSocket(host, port)
    transport.setTimeout(timeout_ms)
    transport = TTransport.TFramedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = YTTokenOpService.Client(protocol)
    transport.open()
    logger.info("Connection successful.")
    return client, transport

def format_timestamp(ts_str: str) -> str:
    """Formats a string timestamp into a human-readable date string."""
    if not ts_str:
        return ""
    try:
        ts_float = float(ts_str)
        # Handle cases where timestamp might be 0 or negative
        if ts_float <= 0:
            return ""
        dt_obj = datetime.datetime.fromtimestamp(ts_float)
        return dt_obj.strftime('%Y-%m-%d %H:%M:%S')
    except (ValueError, TypeError):
        return ts_str  # Return original string if conversion fails
