"""
product_master 제품 조회
"""

import sys
import sqlite3
import os
import json

# UTF-8 인코딩 강제 (Windows 한글 깨짐 방지)
if sys.platform == 'win32':
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

def view_products():
    """product_master 제품 조회"""
    db_path = os.path.join(os.path.dirname(__file__), 'db', 'mileage.db')
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    try:
        # 전체 제품 수
        cursor.execute("SELECT COUNT(*) FROM product_master")
        total = cursor.fetchone()[0]
        print(f"전체 제품 수: {total}개\n")

        # 카테고리별 제품 수
        print("="*80)
        print("카테고리별 제품 수")
        print("="*80)
        cursor.execute("""
            SELECT
                category_name,
                COUNT(*) as count
            FROM product_category_mapping
            GROUP BY category_name
            ORDER BY count DESC
        """)
        for cat, count in cursor.fetchall():
            print(f"{cat:20} : {count:3}개")

        # 제품 목록 (카테고리 포함)
        print("\n" + "="*80)
        print("제품 목록 (카테고리 포함)")
        print("="*80)
        cursor.execute("""
            SELECT
                p.barcode,
                p.product_name,
                GROUP_CONCAT(m.category_name, ', ') as categories,
                p.is_verified
            FROM product_master p
            LEFT JOIN product_category_mapping m ON p.barcode = m.barcode
            GROUP BY p.barcode
            ORDER BY p.product_name
        """)

        for row in cursor.fetchall():
            barcode, name, cats, verified = row
            verified_mark = "[V]" if verified else "[ ]"
            cats_str = cats if cats else "(카테고리 없음)"
            print(f"{verified_mark} {name:30} -> {cats_str}")

    finally:
        conn.close()


if __name__ == '__main__':
    view_products()
