#!/usr/bin/env python3
"""
마일리지 시스템 구축 - patients 테이블에 마일리지 컬럼 추가 및 이력 테이블 생성
"""

import sqlite3
from datetime import datetime
from config import DATABASE_PATH

def add_mileage_system():
    """환자 테이블에 마일리지 컬럼 추가 및 이력 테이블 생성"""
    conn = sqlite3.connect(DATABASE_PATH)
    cursor = conn.cursor()

    # 1. patients 테이블에 마일리지 관련 컬럼 추가
    try:
        cursor.execute("""
            ALTER TABLE patients
            ADD COLUMN mileage_balance INTEGER DEFAULT 0
        """)
        print("✓ mileage_balance 컬럼 추가 완료")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e):
            print("- mileage_balance 컬럼 이미 존재")
        else:
            raise

    try:
        cursor.execute("""
            ALTER TABLE patients
            ADD COLUMN total_mileage_earned INTEGER DEFAULT 0
        """)
        print("✓ total_mileage_earned 컬럼 추가 완료")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e):
            print("- total_mileage_earned 컬럼 이미 존재")
        else:
            raise

    try:
        cursor.execute("""
            ALTER TABLE patients
            ADD COLUMN total_mileage_used INTEGER DEFAULT 0
        """)
        print("✓ total_mileage_used 컬럼 추가 완료")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e):
            print("- total_mileage_used 컬럼 이미 존재")
        else:
            raise

    # 2. 마일리지 거래 이력 테이블 생성
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS mileage_transactions (
            transaction_id INTEGER PRIMARY KEY AUTOINCREMENT,
            patient_id INTEGER REFERENCES patients(patient_id),
            compound_id INTEGER REFERENCES compounds(compound_id),
            transaction_type TEXT NOT NULL, -- EARNED, USED, EXPIRED, ADMIN_ADJUST
            amount INTEGER NOT NULL,
            balance_after INTEGER NOT NULL,
            description TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            created_by TEXT
        )
    """)
    print("✓ mileage_transactions 테이블 생성 완료")

    # 인덱스 생성
    cursor.execute("""
        CREATE INDEX IF NOT EXISTS idx_mileage_transactions_patient
        ON mileage_transactions(patient_id)
    """)
    print("✓ 인덱스 생성 완료")

    # 3. compounds 테이블에 마일리지 사용 컬럼 추가
    try:
        cursor.execute("""
            ALTER TABLE compounds
            ADD COLUMN mileage_used INTEGER DEFAULT 0
        """)
        print("✓ compounds.mileage_used 컬럼 추가 완료")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e):
            print("- compounds.mileage_used 컬럼 이미 존재")
        else:
            raise

    try:
        cursor.execute("""
            ALTER TABLE compounds
            ADD COLUMN mileage_earned INTEGER DEFAULT 0
        """)
        print("✓ compounds.mileage_earned 컬럼 추가 완료")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e):
            print("- compounds.mileage_earned 컬럼 이미 존재")
        else:
            raise

    # 4. 복합 결제를 위한 컬럼 추가
    try:
        cursor.execute("""
            ALTER TABLE compounds
            ADD COLUMN payment_cash INTEGER DEFAULT 0
        """)
        print("✓ payment_cash 컬럼 추가 완료")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e):
            print("- payment_cash 컬럼 이미 존재")
        else:
            raise

    try:
        cursor.execute("""
            ALTER TABLE compounds
            ADD COLUMN payment_card INTEGER DEFAULT 0
        """)
        print("✓ payment_card 컬럼 추가 완료")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e):
            print("- payment_card 컬럼 이미 존재")
        else:
            raise

    try:
        cursor.execute("""
            ALTER TABLE compounds
            ADD COLUMN payment_transfer INTEGER DEFAULT 0
        """)
        print("✓ payment_transfer 컬럼 추가 완료")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e):
            print("- payment_transfer 컬럼 이미 존재")
        else:
            raise

    try:
        cursor.execute("""
            ALTER TABLE compounds
            ADD COLUMN discount_amount INTEGER DEFAULT 0
        """)
        print("✓ discount_amount 컬럼 추가 완료")
    except sqlite3.OperationalError as e:
        if "duplicate column name" in str(e):
            print("- discount_amount 컬럼 이미 존재")
        else:
            raise

    conn.commit()

    # 5. 테스트용 마일리지 데이터 추가 (박주호 회원)
    cursor.execute("""
        SELECT patient_id, name FROM patients
        WHERE name LIKE '%박주호%' OR name LIKE '%주호%'
    """)
    patients = cursor.fetchall()

    if patients:
        for patient in patients:
            print(f"\n박주호 회원 발견: ID={patient[0]}, 이름={patient[1]}")
            # 초기 마일리지 부여
            cursor.execute("""
                UPDATE patients
                SET mileage_balance = 50000,
                    total_mileage_earned = 50000,
                    total_mileage_used = 0
                WHERE patient_id = ?
            """, (patient[0],))

            # 마일리지 이력 추가
            cursor.execute("""
                INSERT INTO mileage_transactions
                (patient_id, transaction_type, amount, balance_after, description, created_by)
                VALUES (?, 'ADMIN_ADJUST', 50000, 50000, '초기 마일리지 부여', 'system')
            """, (patient[0],))
            print(f"  → 50,000 마일리지 부여 완료")
    else:
        print("\n박주호 회원을 찾을 수 없습니다.")

    conn.commit()

    # 현재 patients 테이블 구조 확인
    cursor.execute("PRAGMA table_info(patients)")
    columns = cursor.fetchall()
    print("\n현재 patients 테이블 구조 (마일리지 관련):")
    for col in columns:
        if 'mileage' in col[1].lower():
            print(f"  - {col[1]}: {col[2]}")

    conn.close()
    print("\n마일리지 시스템 구축 완료!")

if __name__ == "__main__":
    add_mileage_system()