# -*- coding: utf-8 -*-
"""
안텔민뽀삐 APC 추가 준비 스크립트
- CD_ITEM_UNIT_MEMBER 구조 확인
- 안텔민킹 레코드 참고
- INSERT 쿼리 생성 (실행 안 함)
"""
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

session = get_db_session('PM_DRUG')

print('=' * 60)
print('1. CD_ITEM_UNIT_MEMBER 테이블 구조')
print('=' * 60)
result = session.execute(text("""
    SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, CHARACTER_MAXIMUM_LENGTH
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'CD_ITEM_UNIT_MEMBER'
    ORDER BY ORDINAL_POSITION
"""))
for r in result:
    nullable = 'NULL' if r.IS_NULLABLE == 'YES' else 'NOT NULL'
    length = f'({r.CHARACTER_MAXIMUM_LENGTH})' if r.CHARACTER_MAXIMUM_LENGTH else ''
    print(f'  {r.COLUMN_NAME}: {r.DATA_TYPE}{length} {nullable}')

print('\n' + '=' * 60)
print('2. 안텔민킹 APC 레코드 (참고용)')
print('=' * 60)
result = session.execute(text("""
    SELECT * FROM CD_ITEM_UNIT_MEMBER 
    WHERE DRUGCODE = 'LB000003157' 
      AND CD_CD_BARCODE LIKE '023%'
"""))
row = result.fetchone()
if row:
    cols = result.keys()
    for col in cols:
        val = getattr(row, col)
        print(f'  {col}: {val}')

print('\n' + '=' * 60)
print('3. 안텔민뽀삐 현재 레코드')
print('=' * 60)
result2 = session.execute(text("""
    SELECT * FROM CD_ITEM_UNIT_MEMBER 
    WHERE DRUGCODE = 'LB000003158'
    ORDER BY SN DESC
"""))
rows = list(result2)
print(f'  총 {len(rows)}개 레코드')
for row in rows[:3]:
    print(f'\n  --- SN: {row.SN} ---')
    cols = result2.keys()
    for col in cols:
        val = getattr(row, col)
        print(f'    {col}: {val}')

print('\n' + '=' * 60)
print('4. 다음 SN 값 확인')
print('=' * 60)
result3 = session.execute(text("SELECT MAX(SN) as max_sn FROM CD_ITEM_UNIT_MEMBER"))
max_sn = result3.fetchone().max_sn
print(f'  현재 MAX(SN): {max_sn}')
print(f'  다음 SN: {max_sn + 1}')

session.close()

print('\n' + '=' * 60)
print('5. PostgreSQL에서 안텔민뽀삐 APC 확인')
print('=' * 60)
from sqlalchemy import create_engine
pg = create_engine('postgresql://admin:trajet6640@192.168.0.87:5432/apdb_master').connect()
result4 = pg.execute(text("""
    SELECT apc, product_name 
    FROM apc 
    WHERE product_name ILIKE '%안텔민%뽀삐%' OR product_name ILIKE '%안텔민%5kg%이하%'
    ORDER BY apc
"""))
for r in result4:
    print(f'  APC: {r.apc}')
    print(f'  제품명: {r.product_name}')
    print()
pg.close()
