"""
Script để lấy tất cả giá trị UNIQUE của các trường metadata từ DB.
Output sẽ được lưu vào file JSON để AI tham khảo khi generate SearchItem.

Usage:
    python tests/extract_db_field_values.py
"""

import asyncio
import json
import logging
import sys
from pathlib import Path

# Add parent dir to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from common.starrocks_connection import get_db_connection

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


# Các trường cần extract distinct values
FIELDS_TO_EXTRACT = [
    "product_line_vn",  # Loại sản phẩm (Áo, Váy, Quần...)
    "product_line_en",  # Loại sản phẩm (Shirt, Dress, Pants...)
    "master_color",  # Màu chính (Đỏ, Trắng, Xanh...)
    "style",  # Phong cách (Basic, Classic, Sporty...)
    "fitting",  # Dáng đồ (Slim, Regular, Loose...)
    "form_sleeve",  # Dáng tay (Short Sleeve, Long Sleeve...)
    "form_neckline",  # Dáng cổ (Round Neck, V-Neck, Polo Collar...)
    "season",  # Mùa (Summer, Winter, Year...)
    "material_group",  # Nhóm chất liệu (Cotton, Knit...)
    "gender_by_product",  # Giới tính (men, women, boy, girl, unisex...)
    "age_by_product",  # Độ tuổi (adult, kid...)
]


async def extract_distinct_values():
    """Extract distinct values for all metadata fields."""
    db = get_db_connection()
    if not db:
        logger.error("Failed to connect to database")
        return None

    result = {}

    for field in FIELDS_TO_EXTRACT:
        logger.info(f"📊 Extracting distinct values for: {field}")

        sql = f"""
        SELECT DISTINCT {field} as value, COUNT(*) as count
        FROM shared_source.magento_product_dimension_with_text_embedding
        WHERE {field} IS NOT NULL AND {field} != ''
        GROUP BY {field}
        ORDER BY count DESC
        """

        try:
            rows = await db.execute_query_async(sql)

            # Format results
            values = []
            for row in rows:
                val = row.get("value", "").strip()
                count = row.get("count", 0)
                if val:  # Only add non-empty values
                    values.append({"value": val, "count": count})

            result[field] = {"total_distinct": len(values), "values": values}

            logger.info(f"  ✅ Found {len(values)} distinct values for {field}")

        except Exception as e:
            logger.error(f"  ❌ Error extracting {field}: {e}")
            result[field] = {"error": str(e)}

    return result


async def main():
    logger.info("🚀 Starting DB field values extraction...")

    result = await extract_distinct_values()

    if not result:
        logger.error("❌ Extraction failed")
        return

    # Save to JSON file
    output_file = Path(__file__).parent / "db_field_values.json"

    with open(output_file, "w", encoding="utf-8") as f:
        json.dump(result, f, ensure_ascii=False, indent=2)

    logger.info(f"✅ Saved results to: {output_file}")

    # Print summary
    print("\n" + "=" * 80)
    print("📊 SUMMARY - DB FIELD VALUES")
    print("=" * 80 + "\n")

    for field, data in result.items():
        if "error" in data:
            print(f"❌ {field}: ERROR - {data['error']}")
        else:
            total = data["total_distinct"]
            top_5 = data["values"][:5]
            print(f"\n🔹 {field}: {total} distinct values")
            print("   Top 5:")
            for item in top_5:
                print(f"     - {item['value']} ({item['count']} products)")

    print("\n" + "=" * 80)
    print(f"📁 Full data saved to: {output_file}")
    print("=" * 80)


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