"""
Database migration script to add Member ID, Blood Group, Address, Validity,
and Emergency Contact columns to the users table, and create the appointment_letters table.
All code contains proper English comments for clarity and maintenance.
"""

import sqlite3
import os

DB_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'instance', 'ngo.db')

def run_migration():
    if not os.path.exists(DB_PATH):
        print(f"Database not found at {DB_PATH}")
        return

    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    print("Checking 'users' table columns...")
    cursor.execute("PRAGMA table_info(users)")
    existing_cols = [row[1] for row in cursor.fetchall()]

    new_user_cols = [
        ("member_id_code", "VARCHAR(50)"),
        ("blood_group", "VARCHAR(10) DEFAULT 'O+'"),
        ("address", "VARCHAR(255) DEFAULT 'Central Hub, New Delhi, India'"),
        ("emergency_contact", "VARCHAR(20) DEFAULT '+91 98765 43210'"),
        ("valid_until", "DATE"),
        ("avatar_url", "VARCHAR(255)")
    ]

    for col_name, col_type in new_user_cols:
        if col_name not in existing_cols:
            print(f"Adding column '{col_name}' to 'users' table...")
            cursor.execute(f"ALTER TABLE users ADD COLUMN {col_name} {col_type}")
        else:
            print(f"Column '{col_name}' already exists in 'users' table.")

    # Create appointment_letters table if it doesn't exist
    print("Checking 'appointment_letters' table...")
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS appointment_letters (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        reference_no VARCHAR(60) NOT NULL UNIQUE,
        user_id INTEGER NOT NULL,
        recipient_name VARCHAR(100) NOT NULL,
        recipient_email VARCHAR(120) NOT NULL,
        recipient_phone VARCHAR(20),
        recipient_address VARCHAR(255),
        designation VARCHAR(100) NOT NULL,
        appointment_date DATE NOT NULL,
        effective_date DATE NOT NULL,
        terms_content TEXT,
        authorized_signatory VARCHAR(120) DEFAULT 'Rajkumar Maurya, General Secretary',
        status VARCHAR(20) DEFAULT 'active',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        emailed_at DATETIME,
        qr_code_token VARCHAR(100),
        FOREIGN KEY (user_id) REFERENCES users (id)
    )
    """)
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_appointment_ref ON appointment_letters(reference_no)")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_appointment_user ON appointment_letters(user_id)")

    conn.commit()
    conn.close()
    print("Migration completed successfully!")

if __name__ == '__main__':
    run_migration()
