# -*- coding: utf-8 -*-
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
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. _get_animal_drugs 시뮬레이션
drug_session = get_db_session('PM_DRUG')
query = 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%'
            ORDER BY U.CHANGE_DATE DESC
        ) AS APC_CODE
    FROM CD_GOODS G
    WHERE G.POS_BOON = '010103'
      AND G.GoodsSelCode = 'B'
    ORDER BY G.GoodsName
""")
rows = drug_session.execute(query).fetchall()

animal_drugs = []
for r in rows:
    animal_drugs.append({
        'code': r.DrugCode,
        'name': r.GoodsName,
        'price': float(r.Saleprice) if r.Saleprice else 0,
        'apc': r.APC_CODE
    })

# 2. _get_animal_drug_rag 시뮬레이션
apc_codes = [d['apc'] for d in animal_drugs if d.get('apc')]
print(f'APC 코드 목록: {apc_codes}\n')

rag_data = {}
if apc_codes:
    pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()
    placeholders = ','.join([f"'{apc}'" for apc in apc_codes])
    result = pg.execute(text(f"""
        SELECT apc, product_name, 
               llm_pharm->>'사용가능 동물' as target_animals,
               llm_pharm->>'분류' as category,
               llm_pharm->>'체중/부위' as dosage_weight,
               llm_pharm->>'기간/용법' as usage_period,
               llm_pharm->>'월령금기' as age_restriction
        FROM apc
        WHERE apc IN ({placeholders})
    """))
    for row in result:
        rag_data[row.apc] = {
            'target_animals': row.target_animals or '정보 없음',
            'category': row.category or '',
            'dosage_weight': row.dosage_weight or '',
            'usage_period': row.usage_period or '',
            'age_restriction': row.age_restriction or ''
        }
    pg.close()

print(f'RAG 데이터: {rag_data}\n')

# 3. available_products_text 생성
print('=== AI에 전달되는 제품 목록 (RAG 포함) ===\n')
for d in animal_drugs:
    if '안텔민' in d['name']:
        line = f"- {d['name']} ({d['price']:,.0f}원)"
        if d.get('apc') and d['apc'] in rag_data:
            info = rag_data[d['apc']]
            details = []
            if info.get('target_animals'):
                details.append(f"대상: {info['target_animals']}")
            if info.get('dosage_weight'):
                details.append(f"용량: {info['dosage_weight']}")
            if info.get('age_restriction'):
                details.append(f"금기: {info['age_restriction']}")
            if details:
                line += f" [{', '.join(details)}]"
        print(line)
