"""
바코드가 있는 제품 샘플 조회
"""

import sys
import os
sys.path.insert(0, os.path.dirname(__file__))

from db.dbsetup import DatabaseManager
from sqlalchemy import text

def check_barcode_samples():
    """바코드가 있는 제품 샘플 조회"""
    db_manager = DatabaseManager()

    try:
        session = db_manager.get_session('PM_PRES')

        # 바코드가 있는 제품 샘플 조회
        query = text("""
            SELECT TOP 10
                S.DrugCode,
                S.BARCODE,
                G.GoodsName,
                S.SL_NM_cost_a as price
            FROM SALE_SUB S
            LEFT JOIN PM_DRUG.dbo.CD_GOODS G ON S.DrugCode = G.DrugCode
            WHERE S.BARCODE IS NOT NULL AND S.BARCODE != ''
            ORDER BY S.SL_NO_order DESC
        """)

        results = session.execute(query).fetchall()

        print('=' * 100)
        print('바코드가 있는 제품 샘플 (최근 10개)')
        print('=' * 100)
        for r in results:
            barcode = r.BARCODE if r.BARCODE else '(없음)'
            goods_name = r.GoodsName if r.GoodsName else '(약품명 없음)'
            print(f'DrugCode: {r.DrugCode:20} | BARCODE: {barcode:20} | 제품명: {goods_name}')
        print('=' * 100)

        # 바코드 통계
        stats_query = text("""
            SELECT
                COUNT(DISTINCT DrugCode) as total_drugs,
                COUNT(DISTINCT BARCODE) as total_barcodes,
                SUM(CASE WHEN BARCODE IS NOT NULL AND BARCODE != '' THEN 1 ELSE 0 END) as with_barcode,
                COUNT(*) as total_sales
            FROM SALE_SUB
        """)

        stats = session.execute(stats_query).fetchone()

        print('\n바코드 통계')
        print('=' * 100)
        print(f'전체 제품 수 (DrugCode):  {stats.total_drugs:,}')
        print(f'바코드 종류 수:            {stats.total_barcodes:,}')
        print(f'바코드가 있는 판매 건수:   {stats.with_barcode:,}')
        print(f'전체 판매 건수:            {stats.total_sales:,}')
        print(f'바코드 보유율:             {stats.with_barcode / stats.total_sales * 100:.2f}%')
        print('=' * 100)

    except Exception as e:
        print(f"오류 발생: {e}")
    finally:
        db_manager.close_all()

if __name__ == '__main__':
    check_barcode_samples()
