import asyncio
import json
import logging
from faststream import FastStream
from faststream.redis import RedisBroker

from config import REDIS_CACHE_URL, REDIS_CACHE_PORT, REDIS_PASSWORD, REDIS_USERNAME
from common.conversation_manager import ConversationManager
from agent.helper import decimal_default

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("Worker")

# Build redis URl
host = REDIS_CACHE_URL or "localhost"
port = REDIS_CACHE_PORT or 6379

if REDIS_USERNAME and REDIS_PASSWORD:
    redis_url = f"redis://{REDIS_USERNAME}:{REDIS_PASSWORD}@{host}:{port}/3"
elif REDIS_PASSWORD:
    redis_url = f"redis://:{REDIS_PASSWORD}@{host}:{port}/3"
else:
    redis_url = f"redis://{host}:{port}/3"

broker = RedisBroker(redis_url)
app = FastStream(broker)
memory = ConversationManager()

@broker.subscriber("chat:save_history")
async def process_save_history(msg: str):
    """
    Worker xử lý lưu lịch sử chat.
    Chạy ở process riêng nên không sợ bị kill do FastAPI reload hay HTTP Timeout.
    Không làm rớt trace Langfuse (vì gọi DB độc lập).
    """
    try:
        data = json.loads(msg)
        identity_key = data.get("identity_key")
        human_query = data.get("human_query")
        ai_response = data.get("ai_response")
        conversation_id = data.get("conversation_id")
        
        if ai_response:
            ai_response_json = json.dumps(ai_response, ensure_ascii=False, default=decimal_default)
            await memory.save_conversation_turn(identity_key, human_query, ai_response_json, conversation_id=conversation_id)
            logger.info(f"✅ [WORKER] Đã lưu history cho user: {identity_key} (conv: {conversation_id})")
    except Exception as e:
        logger.error(f"❌ [WORKER] Save history failed: {e}", exc_info=True)

if __name__ == "__main__":
    logger.info("Khởi động FastStream Worker...")
    asyncio.run(app.run())
