import mysql.connector
import pandas as pd
import db_config

conn = mysql.connector.connect(
    host=db_config.DB_HOST, port=db_config.DB_PORT,
    user=db_config.DB_USER, password=db_config.DB_PASSWORD,
    database=db_config.DB_NAME,
)
cursor = conn.cursor(dictionary=True)

# Vezmi nejnovější import_id pro každou studii
for study in ["77242113UCO3001", "42847922MDD3003"]:
    cursor.execute(
        "SELECT MAX(import_id) AS mid FROM iwrs_import WHERE study=%s AND report_type='patients'",
        (study,),
    )
    row = cursor.fetchone()
    mid = row["mid"]
    print(f"\n=== {study}  (import_id={mid}) ===")

    cursor.execute("""
        SELECT
            v.subject,
            v.actual_date,
            v.scheduled_date,
            v.irt_transaction_no,
            v.irt_transaction_description,
            v.medication_assignment,
            GROUP_CONCAT(v.medication_id ORDER BY v.medication_id SEPARATOR ', ') AS medication_ids,
            SUM(v.quantity_assigned) AS quantity_assigned
        FROM iwrs_subject_visits v
        WHERE v.import_id = %s AND v.study = %s AND v.visit_type = 'Past'
          AND v.irt_transaction_no IS NOT NULL
        GROUP BY v.subject, v.actual_date, v.scheduled_date, v.irt_transaction_no,
                 v.irt_transaction_description, v.medication_assignment
        ORDER BY v.subject, v.actual_date
        LIMIT 20
    """, (mid, study))

    rows = cursor.fetchall()
    df = pd.DataFrame(rows)
    if df.empty:
        print("  Žádná data.")
    else:
        pd.set_option("display.max_columns", None)
        pd.set_option("display.width", 200)
        pd.set_option("display.max_colwidth", 30)
        print(df.to_string(index=False))

cursor.close()
conn.close()
