"""
Test Conversation Manager - Timestamp Vietnam Timezone
Test xem timestamp lưu có đúng giờ VN không
"""

import asyncio
from datetime import datetime, timedelta, timezone


async def test_timestamp():
    """Test current Vietnam time and save conversation"""

    # 1. Check current Vietnam time
    vietnam_tz = timezone(timedelta(hours=7))
    now = datetime.now(vietnam_tz)

    print("=" * 60)
    print("🕐 VIETNAM TIMEZONE TEST")
    print("=" * 60)
    print(f"Current Vietnam Time: {now}")
    print(f"Hour: {now.hour}")
    print(f"Minute: {now.minute}")
    print(f"Second: {now.second}")
    print(f"Timezone: {now.tzinfo}")
    print()

    # 2. Test start/end of day calculation
    start_of_day = now.replace(hour=0, minute=0, second=0, microsecond=0)
    end_of_day = now.replace(hour=23, minute=59, second=59, microsecond=999999)

    print("📅 TODAY'S RANGE:")
    print(f"Start: {start_of_day}")
    print(f"End: {end_of_day}")
    print()

    # 3. Test actual save to DB
    print("💾 TESTING SAVE TO DATABASE...")
    try:
        import sys
        from pathlib import Path

        sys.path.insert(0, str(Path(__file__).parent.parent))

        from common.conversation_manager import get_conversation_manager

        manager = await get_conversation_manager()

        # Save test conversation
        test_identity = f"test_tz_{now.strftime('%H%M%S')}"
        human_msg = f"Test message at {now.strftime('%Y-%m-%d %H:%M:%S')} VN time"
        ai_msg = f"AI response at {now.strftime('%Y-%m-%d %H:%M:%S')} VN time"

        await manager.save_conversation_turn(identity_key=test_identity, human_message=human_msg, ai_message=ai_msg)

        print(f"✅ Saved conversation for: {test_identity}")
        print(f"   Human: {human_msg}")
        print(f"   AI: {ai_msg}")
        print()

        # 4. Retrieve and verify
        print("🔍 RETRIEVING FROM DATABASE...")
        history = await manager.get_chat_history(test_identity, limit=10)

        if history:
            print(f"✅ Retrieved {len(history)} messages:")
            for idx, msg in enumerate(history, 1):
                timestamp = msg["timestamp"]
                print(f"   [{idx}] {timestamp} | is_human={msg['is_human']}")
                print(f"       Message: {msg['message'][:50]}...")

            # Verify timestamp is in today's range
            first_msg_time = history[0]["timestamp"]
            if start_of_day <= first_msg_time <= end_of_day:
                print()
                print("✅✅✅ TIMESTAMP CORRECT! Message is within today's range!")
            else:
                print()
                print("❌ TIMESTAMP WRONG! Message is outside today's range!")
                print(f"   Expected: {start_of_day} to {end_of_day}")
                print(f"   Got: {first_msg_time}")
        else:
            print("❌ No history found!")

    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback

        traceback.print_exc()

    print()
    print("=" * 60)
    print("Test completed!")
    print("=" * 60)


if __name__ == "__main__":
    import sys

    if sys.platform == "win32":
        # Fix for Windows ProactorEventLoop issue with psycopg
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    asyncio.run(test_timestamp())
