"""
Database Migration Script for Module 9:
Member Referral System (Membership & Donation Referral Tracking) and Member Block/Unblock.
All code contains proper English comments for clarity and maintenance.
"""

import sqlite3
import os
import sys

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

def migrate():
    print(f"Connecting to database at: {DB_PATH}")
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    # 1. Inspect existing columns in 'users'
    cursor.execute("PRAGMA table_info(users)")
    user_cols = [row[1] for row in cursor.fetchall()]
    print(f"Existing columns in 'users': {user_cols}")

    # Add referral_code to users if not present
    if "referral_code" not in user_cols:
        print("Adding 'referral_code' column to 'users' table...")
        cursor.execute("ALTER TABLE users ADD COLUMN referral_code VARCHAR(50)")
        print("  -> Column 'referral_code' added successfully.")
    else:
        print("  -> 'referral_code' already exists in 'users'.")

    # Add referred_by_id to users if not present
    if "referred_by_id" not in user_cols:
        print("Adding 'referred_by_id' column to 'users' table...")
        cursor.execute("ALTER TABLE users ADD COLUMN referred_by_id INTEGER REFERENCES users(id)")
        print("  -> Column 'referred_by_id' added successfully.")
    else:
        print("  -> 'referred_by_id' already exists in 'users'.")

    # 2. Inspect existing columns in 'donations'
    cursor.execute("PRAGMA table_info(donations)")
    donation_cols = [row[1] for row in cursor.fetchall()]
    print(f"Existing columns in 'donations': {donation_cols}")

    # Add referred_by_id to donations if not present
    if "referred_by_id" not in donation_cols:
        print("Adding 'referred_by_id' column to 'donations' table...")
        cursor.execute("ALTER TABLE donations ADD COLUMN referred_by_id INTEGER REFERENCES users(id)")
        print("  -> Column 'referred_by_id' added successfully.")
    else:
        print("  -> 'referred_by_id' already exists in 'donations'.")

    # Add referral_code to donations if not present
    if "referral_code" not in donation_cols:
        print("Adding 'referral_code' column to 'donations' table...")
        cursor.execute("ALTER TABLE donations ADD COLUMN referral_code VARCHAR(50)")
        print("  -> Column 'referral_code' added successfully.")
    else:
        print("  -> 'referral_code' already exists in 'donations'.")

    # 3. Populate default referral_code for any users that have NULL
    cursor.execute("SELECT id, member_id_code FROM users WHERE referral_code IS NULL OR referral_code = ''")
    users_needing_code = cursor.fetchall()
    print(f"Found {len(users_needing_code)} users requiring referral code generation.")

    for uid, mem_code in users_needing_code:
        # Standardize referral code format e.g. REF0001
        ref_code = f"REF{uid:04d}"
        cursor.execute("UPDATE users SET referral_code = ? WHERE id = ?", (ref_code, uid))
        print(f"  * Generated referral code '{ref_code}' for User ID {uid}")

    # 4. Create indices for fast lookup
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_users_referral_code ON users(referral_code)")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_users_referred_by ON users(referred_by_id)")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_donations_referred_by ON donations(referred_by_id)")
    cursor.execute("CREATE INDEX IF NOT EXISTS idx_donations_referral_code ON donations(referral_code)")

    conn.commit()
    conn.close()
    print("\n[SUCCESS] Module 9 database migration completed successfully!")

if __name__ == "__main__":
    migrate()
