
import asyncio
import json
import logging
import os
import sys
import warnings

# Ensure we can import from backend root
current_dir = os.path.dirname(os.path.abspath(__file__))
backend_root = os.path.dirname(current_dir)
sys.path.append(backend_root)

# Setup logging
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

from agent.tools.data_retrieval_tool import SearchItem, data_retrieval_tool
from common.starrocks_connection import StarRocksConnection

# Suppress ResourceWarning for unclosed sockets/loops
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=ResourceWarning)

async def test_search_cases():
    """
    Run specific search cases to verify filtering logic.
    """
    test_cases = [
        {
            "name": "Red Skirt (Chân váy đỏ)",
            "query": "chân váy màu đỏ",
            "search_item": SearchItem(
                query="chân váy đỏ",
                product_name="chân váy",
                master_color="đỏ",
                magento_ref_code=None, price_min=None, price_max=None,
                gender_by_product=None, age_by_product=None, form_sleeve=None, style=None,
                fitting=None, form_neckline=None, material_group=None, season=None, product_line_vn=None
            ),
            "expect": {
                "product_matches": ["skirt", "chân váy"],
                "color_matches": ["red", "đỏ"]
            }
        },
        {
            "name": "Red Pants (Quần đỏ)",
            "query": "quần đỏ",
            "search_item": SearchItem(
                query="quần đỏ",
                product_name="quần",
                master_color="đỏ",
                magento_ref_code=None, price_min=None, price_max=None,
                gender_by_product=None, age_by_product=None, form_sleeve=None, style=None,
                fitting=None, form_neckline=None, material_group=None, season=None, product_line_vn=None
            ),
             "expect": {
                "product_matches": ["pants", "quần", "trousers"],
                "color_matches": ["red", "đỏ"]
            }
        },
        {
            "name": "Wool Material (Vải len)",
            "query": "đồ len",
            "search_item": SearchItem(
                query="đồ len",
                material_group="len",
                product_name=None, magento_ref_code=None, price_min=None, price_max=None,
                gender_by_product=None, age_by_product=None, master_color=None, form_sleeve=None, style=None,
                fitting=None, form_neckline=None, season=None, product_line_vn=None
            ),
             "expect": {
                "material_matches": ["wool", "len", "cashmere"]
            }
        }
    ]

    print("\n" + "="*80)
    print("🚀 STARTING DYNAMIC SEARCH VERIFICATION")
    print("="*80 + "\n")

    try:
        for case in test_cases:
            print(f"🔍 Testing Case: {case['name']}")
            print(f"   Query: {case['query']}")
            
            try:
                case['result_status'] = "FAIL"
                # We call the tool. Format: {"searches": [item]}
                result_json = await data_retrieval_tool.ainvoke({"searches": [case["search_item"]]})
                result = json.loads(result_json)
                
                if result["status"] != "success":
                    case['result_detail'] = f"Tool Error: {result.get('message')}"
                    print(f"   ❌ FAILED: {case['result_detail']}")
                    continue
                    
                products = result["results"]
                filter_info = result["filter_info"]
                
                print(f"   Found {len(products)} products.")

                if not products:
                    case['result_status'] = "NO_RESULTS"
                    detail = "0 products found"
                    if filter_info.get("message"):
                         detail += f" [Msg: {filter_info.get('message')}]"
                    case['result_detail'] = detail
                    print(f"   ⚠️ {detail}")
                    continue

                # Verify first few products
                match_count = 0
                check_limit = min(5, len(products))
                
                for i in range(check_limit):
                    p = products[i]
                    desc = p.get("description_text_full", "") or p.get("description", "")
                    desc = desc.lower()
                    is_valid = True
                    
                    # Check Color
                    if "color_matches" in case["expect"]:
                       found_color = False
                       for c in case["expect"]["color_matches"]:
                           if c in desc: 
                               found_color = True
                               break
                       if not found_color:
                           is_valid = False
                           # print(f"      ❌ Product {i}: Color matches not found")
                    
                    # Check Material
                    if "material_matches" in case["expect"]:
                       found_mat = False
                       for m in case["expect"]["material_matches"]:
                           if m in desc: 
                               found_mat = True
                               break
                       if not found_mat:
                           is_valid = False
                           # print(f"      ❌ Product {i}: Material matches not found")

                    if is_valid:
                        match_count += 1
                
                if match_count == check_limit:
                     case['result_status'] = "PASS"
                     case['result_detail'] = f"Top {check_limit} products match criteria"
                     print(f"   ✅ VERIFIED: {case['result_detail']}")
                else:
                     case['result_status'] = "PARTIAL"
                     case['result_detail'] = f"{match_count}/{check_limit} matched criteria"
                     print(f"   ⚠️ PARTIAL: {case['result_detail']}")

            except Exception as e:
                case['result_status'] = "ERROR"
                case['result_detail'] = str(e)
                print(f"   ❌ EXCEPTION: {e}")
            
            print("-" * 50)
            
    finally:
        print("\n" + "="*80)
        print("📊 TEST SUMMARY")
        print("="*80)
        for case in test_cases:
             status = case.get('result_status', 'UNKNOWN')
             detail = case.get('result_detail', '')
             print(f"🔹 {case['name']:<30} | {status:<10} | {detail}")
        print("="*80)
        
        # CLEANUP
        # print("\n🧹 Cleaning up connections...")
        await StarRocksConnection.clear_pool()

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