#!/usr/bin/env python3
"""
Test script for hwGpt thread management functionality.
"""

import sys
import os
from datetime import datetime, timezone

# Add the project root to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from src.utils.db import get_db_session
from src.marketing.apps.hwGpt.thread_service import ThreadService
from src.marketing.apps.hwGpt.thread_history_service import ThreadHistoryService
from src.marketing.apps.hwGpt import schema


def test_thread_management():
    """Test thread creation and management."""
    print("🧪 Testing hwGpt Thread Management")
    print("=" * 50)
    
    # Test parameters
    store_id = 35
    user_id = 1
    branch_id = None
    
    try:
        # Get database session
        db = get_db_session()
        
        # Initialize services
        thread_service = ThreadService(db)
        history_service = ThreadHistoryService(db)
        
        print(f"📊 Testing with store_id: {store_id}, user_id: {user_id}")
        print()
        
        # Test 1: Create a new thread
        print("1️⃣ Creating new thread...")
        thread_data = schema.ThreadCreateRequest(
            store_id=store_id,
            branch_id=branch_id,
            user_id=user_id,
            title="Test Chat Thread",
            description="A test thread for hwGpt functionality",
            thread_type="general"
        )
        
        thread = thread_service.create_thread(thread_data)
        print(f"✅ Thread created: ID {thread.id}, Title: {thread.title}")
        print(f"   Store: {thread.store_id}, User: {thread.user_id}")
        print(f"   Type: {thread.thread_type}, Active: {thread.is_active}")
        print()
        
        # Test 2: Add messages to the thread
        print("2️⃣ Adding messages to thread...")
        
        # User message
        user_message = schema.MessageCreateRequest(
            thread_id=thread.id,
            user_id=user_id,
            role="user",
            content="Hello! This is a test message from the user.",
            message_type="text"
        )
        
        user_msg_response = history_service.add_message(user_message)
        print(f"✅ User message added: ID {user_msg_response.id}")
        print(f"   Content: {user_msg_response.content[:50]}...")
        print()
        
        # Assistant message
        assistant_message = schema.MessageCreateRequest(
            thread_id=thread.id,
            user_id=user_id,
            role="assistant",
            content="Hello! I'm the AI assistant. How can I help you today?",
            message_type="text",
            model_used="gpt-4"
        )
        
        assistant_msg_response = history_service.add_message(assistant_message)
        print(f"✅ Assistant message added: ID {assistant_msg_response.id}")
        print(f"   Content: {assistant_msg_response.content[:50]}...")
        print(f"   Model: {assistant_msg_response.model_used}")
        print()
        
        # Test 3: Get thread with messages
        print("3️⃣ Retrieving thread with messages...")
        thread_with_messages = thread_service.get_thread_with_messages(thread.id, user_id)
        
        if thread_with_messages:
            print(f"✅ Thread retrieved: {thread_with_messages.thread.title}")
            print(f"   Total messages: {thread_with_messages.total_messages}")
            print(f"   Messages:")
            for i, msg in enumerate(thread_with_messages.messages):
                print(f"     {i+1}. [{msg.role.upper()}] {msg.content[:40]}...")
        else:
            print("❌ Failed to retrieve thread with messages")
        print()
        
        # Test 4: List user threads
        print("4️⃣ Listing user threads...")
        thread_list = thread_service.list_user_threads(
            user_id=user_id,
            store_id=store_id,
            page=1,
            page_size=10
        )
        
        print(f"✅ Found {thread_list.total_threads} threads")
        print(f"   Page: {thread_list.page}, Page Size: {thread_list.page_size}")
        for t in thread_list.threads:
            print(f"   - {t.title} (ID: {t.id}, Messages: {t.message_count})")
        print()
        
        # Test 5: Get thread statistics
        print("5️⃣ Getting thread statistics...")
        thread_stats = thread_service.get_thread_stats(user_id, store_id)
        
        print(f"✅ Thread Statistics:")
        print(f"   Total threads: {thread_stats['total_threads']}")
        print(f"   Active threads: {thread_stats['active_threads']}")
        print(f"   Archived threads: {thread_stats['archived_threads']}")
        print(f"   Total messages: {thread_stats['total_messages']}")
        print()
        
        # Test 6: Get message statistics
        print("6️⃣ Getting message statistics...")
        message_stats = history_service.get_message_stats(user_id, store_id, days=30)
        
        print(f"✅ Message Statistics (Last 30 days):")
        print(f"   Total messages: {message_stats['total_messages']}")
        print(f"   User messages: {message_stats['user_messages']}")
        print(f"   Assistant messages: {message_stats['assistant_messages']}")
        print(f"   System messages: {message_stats['system_messages']}")
        print(f"   Text messages: {message_stats['text_messages']}")
        print(f"   Image messages: {message_stats['image_messages']}")
        print(f"   File messages: {message_stats['file_messages']}")
        print()
        
        # Test 7: Search messages
        print("7️⃣ Searching messages...")
        search_results = history_service.search_messages(
            user_id=user_id,
            query="test",
            store_id=store_id,
            limit=10
        )
        
        print(f"✅ Search results for 'test': {len(search_results)} messages found")
        for msg in search_results:
            print(f"   - [{msg.role}] {msg.content[:50]}...")
        print()
        
        # Test 8: Update thread
        print("8️⃣ Updating thread...")
        update_data = schema.ThreadUpdateRequest(
            title="Updated Test Thread",
            description="This thread has been updated for testing purposes"
        )
        
        updated_thread = thread_service.update_thread(thread.id, user_id, update_data)
        if updated_thread:
            print(f"✅ Thread updated: {updated_thread.title}")
            print(f"   Description: {updated_thread.description}")
        else:
            print("❌ Failed to update thread")
        print()
        
        # Test 9: Archive thread
        print("9️⃣ Archiving thread...")
        if thread_service.archive_thread(thread.id, user_id):
            print("✅ Thread archived successfully")
        else:
            print("❌ Failed to archive thread")
        print()
        
        # Test 10: Unarchive thread
        print("🔟 Unarchiving thread...")
        if thread_service.unarchive_thread(thread.id, user_id):
            print("✅ Thread unarchived successfully")
        else:
            print("❌ Failed to unarchive thread")
        print()
        
        db.close()
        
    except Exception as e:
        print(f"❌ Error during testing: {str(e)}")
        import traceback
        traceback.print_exc()
        
        if 'db' in locals():
            db.close()


if __name__ == "__main__":
    print("🚀 hwGpt Thread Management Test")
    print("=" * 50)
    
    test_thread_management()
    
    print("\n🎉 All tests completed!")
