import os
import sys
import asyncio
from datetime import datetime
from zoneinfo import ZoneInfo

# Add parent dir to path so we can import from backend
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from common.cache import redis_cache

async def main():
    device_id = "b9ae861478939edad0dc3c77db8f0499"
    print(f"🔄 Bắt đầu reset cho device_id: {device_id}")

    await redis_cache.initialize()
    client = redis_cache.get_client()

    if not client:
        print("❌ Lỗi: Không thể kết nối Redis")
        return

    try:
        # 1. Clear conversation history
        history_key = f"identity_key_history:{device_id}"
        deleted_history = await client.delete(history_key)
        print(f"✅ Đã xóa lịch sử chat: {history_key} (Keys deleted: {deleted_history})")

        # 2. Clear user insight
        insight_key = f"identity_key_insight:{device_id}"
        deleted_insight = await client.delete(insight_key)
        print(f"✅ Đã xóa user insight: {insight_key} (Keys deleted: {deleted_insight})")

        # 3. Add 100 limit chat for guest
        # Format msg_limit:YYYY-MM-DD:device_id
        tz = ZoneInfo("Asia/Ho_Chi_Minh")
        today = datetime.now(tz).strftime("%Y-%m-%d")
        limit_key = f"msg_limit:{today}:{device_id}"

        # Bằng cách set 'guest' trong Hash về số âm (-90), user sẽ có tổng 100 lượt chat
        # (vì guest_limit mặc định là 10, guest_used = -90 -> remaining = 10 - (-90) = 100)
        await client.hset(limit_key, "guest", -90)

        # Set expire until midnight so it cleans up naturally
        now = datetime.now(tz)
        reset_time = now.replace(hour=0, minute=0, second=0, microsecond=0)
        from datetime import timedelta
        if now >= reset_time:
            reset_time = reset_time + timedelta(days=1)
        seconds_until_reset = int((reset_time - now).total_seconds())
        await client.expire(limit_key, seconds_until_reset)

        print(f"✅ Đã reset và thêm 100 lượt chat vào limit_key: {limit_key}")
        print("🎉 Hoàn thành!")
    except Exception as e:
        print(f"❌ Lỗi: {e}")
    finally:
        # Close redis connection
        await client.close()

if __name__ == "__main__":
    asyncio.run(main())
