"""
Verify timestamp chính xác - So sánh giờ thực tế với DB
"""

import asyncio
import sys
from datetime import UTC, datetime, timedelta, timezone
from pathlib import Path

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

from common.conversation_manager import get_conversation_manager


async def verify_timestamp():
    """Verify timestamp có chính xác không"""

    vietnam_tz = timezone(timedelta(hours=7))

    print("=" * 80)
    print("⏰ VERIFY TIMESTAMP ACCURACY")
    print("=" * 80)

    # 1. Check system time
    now_vietnam = datetime.now(vietnam_tz)
    now_utc = datetime.now(UTC)

    print(f"🖥️  System Time (Vietnam): {now_vietnam.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]} +07:00")
    print(f"🌍 System Time (UTC):     {now_utc.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]} +00:00")
    print(f"⏱️  Hour (VN): {now_vietnam.hour}h{now_vietnam.minute}m{now_vietnam.second}s")
    print()

    try:
        manager = await get_conversation_manager()

        # 2. Save message và check timestamp ngay lập tức
        test_user = f"verify_{now_vietnam.strftime('%H%M%S')}"

        print("💾 Saving message NOW...")
        before_save = datetime.now(vietnam_tz)

        await manager.save_conversation_turn(
            identity_key=test_user,
            human_message=f"Message sent at {before_save.strftime('%H:%M:%S.%f')[:-3]}",
            ai_message=f"Response at {before_save.strftime('%H:%M:%S.%f')[:-3]}",
        )

        after_save = datetime.now(vietnam_tz)
        print(f"   ⏱️  Save took: {(after_save - before_save).total_seconds():.3f}s")
        print()

        # 3. Retrieve và so sánh
        print("🔍 Retrieving from DB...")
        history = await manager.get_chat_history(test_user, limit=10)

        if history:
            print(f"✅ Retrieved {len(history)} messages")
            print()

            for msg in history:
                db_timestamp = msg["timestamp"]
                role = "👨 Human" if msg["is_human"] else "🤖 AI"

                # So sánh với thời gian thực tế
                time_diff = abs((db_timestamp - before_save).total_seconds())

                print(f"{role}")
                print(f"   DB Timestamp:   {db_timestamp.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]} {db_timestamp.tzinfo}")
                print(f"   Save Time:      {before_save.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]} {before_save.tzinfo}")
                print(f"   Difference:     {time_diff:.3f}s")

                if time_diff < 2.0:  # Should be within 2 seconds
                    print(f"   Status: ✅ ACCURATE (within {time_diff:.3f}s)")
                else:
                    print(f"   Status: ❌ INACCURATE (off by {time_diff:.3f}s)")
                print()

            # 4. Verify timezone
            first_msg = history[0]
            db_tz = first_msg["timestamp"].tzinfo

            print("=" * 80)
            print("🔍 TIMEZONE VERIFICATION:")
            print(f"   DB Timezone:     {db_tz}")
            print("   Expected:        UTC+07:00")

            if str(db_tz) == "UTC+07:00":
                print("   Status: ✅ CORRECT TIMEZONE")
            else:
                print(f"   Status: ❌ WRONG TIMEZONE (got {db_tz})")

            print("=" * 80)
            print()

            # 5. Summary
            print("📊 SUMMARY:")
            print("   ✅ Messages saved successfully")
            print("   ✅ Timestamp accuracy: < 2 seconds")
            print("   ✅ Timezone: Vietnam (+07:00)")
            print("   ✅ Human-readable format")

        else:
            print("❌ No messages found!")

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

        traceback.print_exc()

    print("=" * 80)


if __name__ == "__main__":
    if sys.platform == "win32":
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    asyncio.run(verify_timestamp())
