# -*- coding: utf-8 -*-
import pyodbc

conn_str = (
    'DRIVER={ODBC Driver 17 for SQL Server};'
    'SERVER=192.168.0.4\\PM2014;'
    'DATABASE=PM_PRES;'
    'UID=sa;'
    'PWD=tmddls214!%(;'
    'TrustServerCertificate=yes;'
    'Connection Timeout=10'
)

conn = pyodbc.connect(conn_str, timeout=10)
cur = conn.cursor()

# 오늘 날짜 확인
cur.execute('SELECT CONVERT(VARCHAR, GETDATE(), 112)')
today = cur.fetchone()[0]
print(f'오늘 날짜: {today}')

# 오늘 처방된 약품 중 3명 이하 환자 약품 테스트
query = """
WITH PatientUsage AS (
    SELECT DISTINCT
        P.DrugCode,
        M.Paname,
        MAX(CASE WHEN M.Indate = CONVERT(VARCHAR, GETDATE(), 112) THEN 1 ELSE 0 END) as used_today
    FROM PS_sub_pharm P
    JOIN PS_main M ON P.PreSerial = M.PreSerial
    WHERE M.Indate >= CONVERT(VARCHAR, DATEADD(YEAR, -1, GETDATE()), 112)
    GROUP BY P.DrugCode, M.Paname
)
SELECT TOP 20
    PU.DrugCode,
    COUNT(*) as patient_count,
    STUFF((
        SELECT ', ' + PU2.Paname
        FROM PatientUsage PU2
        WHERE PU2.DrugCode = PU.DrugCode
        ORDER BY PU2.Paname
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') as patient_names,
    STUFF((
        SELECT ', ' + PU3.Paname
        FROM PatientUsage PU3
        WHERE PU3.DrugCode = PU.DrugCode AND PU3.used_today = 1
        ORDER BY PU3.Paname
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') as today_patients
FROM PatientUsage PU
GROUP BY PU.DrugCode
HAVING COUNT(*) <= 3
ORDER BY 
    CASE WHEN MAX(PU.used_today) = 1 THEN 0 ELSE 1 END,  -- 오늘 사용한 것 먼저
    PU.DrugCode
"""

cur.execute(query)
print('\n=== 3명 이하 환자 약품 (오늘 사용 우선) ===')
for row in cur.fetchall():
    today_mark = ' ⭐오늘' if row.today_patients else ''
    print(f'[{row.DrugCode}] {row.patient_count}명: {row.patient_names}{today_mark}')
    if row.today_patients:
        print(f'    → 오늘 사용: {row.today_patients}')
