# -*- coding: utf-8 -*-
"""APC 매칭 성능 측정"""
import sys, io, time
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')

from db.dbsetup import get_db_session
from sqlalchemy import text, create_engine

print('=== APC 매칭 성능 측정 ===\n')

# 1. MSSQL: 동물약 + APC 조회
start = time.time()
session = get_db_session('PM_DRUG')
result = session.execute(text("""
    SELECT G.DrugCode, G.GoodsName,
        (SELECT TOP 1 U.CD_CD_BARCODE FROM CD_ITEM_UNIT_MEMBER U 
         WHERE U.DRUGCODE = G.DrugCode AND U.CD_CD_BARCODE LIKE '023%') AS APC_CODE
    FROM CD_GOODS G 
    WHERE G.POS_BOON = '010103' AND G.GoodsSelCode = 'B'
"""))
mssql_rows = list(result)
no_apc = [r for r in mssql_rows if not r.APC_CODE]
has_apc = [r for r in mssql_rows if r.APC_CODE]
mssql_time = time.time() - start
print(f'1. MSSQL 동물약 조회: {mssql_time:.3f}초')
print(f'   - 총 제품: {len(mssql_rows)}개')
print(f'   - APC 있음: {len(has_apc)}개 ✅')
print(f'   - APC 없음: {len(no_apc)}개 ❌')

# 2. PostgreSQL 연결 + 매칭 검색
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()

# 샘플 매칭 테스트
sample_count = min(5, len(no_apc))
start = time.time()
match_count = 0
for drug in no_apc[:sample_count]:
    search_name = drug.GoodsName.replace('(판)', '').split('(')[0].strip()
    res = pg.execute(text("""
        SELECT apc, product_name FROM apc 
        WHERE product_name ILIKE :p LIMIT 5
    """), {'p': f'%{search_name}%'})
    if list(res):
        match_count += 1
pg_search_time = time.time() - start
per_search = pg_search_time / sample_count if sample_count > 0 else 0
print(f'\n2. PostgreSQL 매칭 검색: {pg_search_time:.3f}초 ({sample_count}개 샘플)')
print(f'   - 건당 소요: {per_search*1000:.1f}ms')
print(f'   - 매칭 성공: {match_count}/{sample_count}')
print(f'   - 예상 전체: {per_search * len(no_apc):.1f}초 ({len(no_apc)}개)')

# 3. APC 테이블 통계
start = time.time()
total_apc = pg.execute(text("SELECT COUNT(*) FROM apc")).scalar()
with_image = pg.execute(text("SELECT COUNT(*) FROM apc WHERE image_url1 IS NOT NULL AND image_url1 != ''")).scalar()
pg.close()
print(f'\n3. APDB 통계:')
print(f'   - 전체 APC: {total_apc:,}개')
print(f'   - 이미지 있음: {with_image:,}개 ({with_image/total_apc*100:.1f}%)')

# 4. CD_ITEM_UNIT_MEMBER 구조 확인
print(f'\n4. 현재 APC 매핑 상태:')
for r in has_apc[:5]:
    print(f'   ✅ {r.GoodsName[:25]:<25} → {r.APC_CODE}')

session.close()
print('\n=== 측정 완료 ===')
