import json
import redis
import os
import logging

logger = logging.getLogger(__name__)

REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
REDIS_DB   = int(os.getenv("REDIS_DB", 0))
REDIS_TTL  = int(os.getenv("REDIS_EXPIRATION", 3600))

# Max messages kept per conversation; max chars stored per message
HISTORY_LIMIT = 20
CONTENT_LIMIT = 4000

def _make_client():
    client = redis.Redis(
        host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB,
        decode_responses=True, socket_connect_timeout=3,
        socket_timeout=3, retry_on_timeout=True,
    )
    client.ping()
    return client

try:
    _r = _make_client()
    logger.info("✓ Redis chat history connected")
except Exception as e:
    logger.warning(f"Redis chat history unavailable: {e} — history will fall back to DB")
    _r = None


def _get_redis():
    """Return live Redis client, attempting reconnect if previously unavailable."""
    global _r
    if _r is not None:
        return _r
    try:
        _r = _make_client()
        logger.info("Redis chat history reconnected")
    except Exception:
        pass
    return _r


def _key(company_id, conversation_id: str) -> str:
    return f"chat:{company_id}:{conversation_id}"


def _push(company_id, conversation_id: str, role: str, content: str) -> None:
    """Append one message to the conversation list and keep at most HISTORY_LIMIT entries."""
    client = _get_redis()
    if not client:
        return
    try:
        payload = json.dumps({"role": role, "content": content[:CONTENT_LIMIT]})
        key = _key(str(company_id), conversation_id)
        pipe = client.pipeline()
        pipe.rpush(key, payload)
        pipe.ltrim(key, -HISTORY_LIMIT, -1)
        pipe.expire(key, REDIS_TTL)
        pipe.execute()
    except Exception as e:
        logger.warning(f"Redis chat write failed: {e}")


def add_user_message(company_id, conversation_id: str, content: str) -> None:
    _push(company_id, conversation_id, "user", content)


def add_ai_message(company_id, conversation_id: str, content: str) -> None:
    _push(company_id, conversation_id, "assistant", content)


def get_messages(company_id, conversation_id: str) -> list:
    """Returns list of {"role": "user"|"assistant", "content": str}. Empty list on failure."""
    client = _get_redis()
    if not client:
        return []
    try:
        key = _key(str(company_id), conversation_id)
        raw = client.lrange(key, 0, -1)
        return [json.loads(m) for m in raw]
    except Exception as e:
        logger.warning(f"Redis chat read failed: {e}")
        return []


def clear_chat(company_id, conversation_id: str) -> None:
    client = _get_redis()
    if not client:
        return
    try:
        client.delete(_key(str(company_id), conversation_id))
    except Exception as e:
        logger.warning(f"Redis chat clear failed: {e}")
