# -*- coding: utf-8 -*-
"""
동물약 일괄 APC 매칭 - 후보 찾기
"""
import sys, io
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

# 1. MSSQL 동물약 (APC 없는 것만)
session = get_db_session('PM_DRUG')
result = session.execute(text("""
    SELECT 
        G.DrugCode,
        G.GoodsName,
        G.Saleprice,
        (
            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'
    ORDER BY G.GoodsName
"""))

no_apc = []
for row in result:
    if not row.APC_CODE:
        no_apc.append({
            'code': row.DrugCode,
            'name': row.GoodsName,
            'price': row.Saleprice
        })

session.close()

print(f'=== APC 없는 동물약: {len(no_apc)}개 ===\n')

# 2. PostgreSQL에서 매칭 후보 찾기
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()

matches = []
for drug in no_apc:
    name = drug['name']
    # 제품명에서 검색 키워드 추출
    # (판) 제거, 괄호 내용 제거
    search_name = name.replace('(판)', '').split('(')[0].strip()
    
    # PostgreSQL 검색
    result = pg.execute(text("""
        SELECT apc, product_name, 
               llm_pharm->>'사용가능 동물' as target,
               llm_pharm->>'분류' as category
        FROM apc 
        WHERE product_name ILIKE :pattern
        ORDER BY LENGTH(product_name)
        LIMIT 5
    """), {'pattern': f'%{search_name}%'})
    
    candidates = list(result)
    if candidates:
        matches.append({
            'mssql': drug,
            'candidates': candidates
        })
        print(f'✅ {name}')
        for c in candidates[:2]:
            print(f'   → {c.apc}: {c.product_name[:40]}... [{c.target or "?"}]')
    else:
        print(f'❌ {name} - 매칭 없음')

pg.close()

print(f'\n=== 요약 ===')
print(f'APC 없는 제품: {len(no_apc)}개')
print(f'매칭 후보 있음: {len(matches)}개')
print(f'매칭 없음: {len(no_apc) - len(matches)}개')
