"""
Database migration script to add payment gateway tracking and auto-pay recurring mandate
columns to the 'donations' table, and ensure the 'autopay_subscriptions' table is created.
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()

    # 1. Ensure autopay_subscriptions table exists
    print("Checking 'autopay_subscriptions' table...")
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS autopay_subscriptions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        mandate_code VARCHAR(60) NOT NULL UNIQUE,
        donor_name VARCHAR(120) NOT NULL,
        donor_email VARCHAR(120) NOT NULL,
        donor_phone VARCHAR(20),
        donor_pan VARCHAR(10),
        amount NUMERIC(10, 2) NOT NULL,
        currency VARCHAR(10) DEFAULT 'INR',
        billing_day INTEGER DEFAULT 5,
        gateway VARCHAR(50) DEFAULT 'mock_simulator',
        gateway_subscription_id VARCHAR(100),
        gateway_customer_id VARCHAR(100),
        status VARCHAR(20) DEFAULT 'active',
        cycles_completed INTEGER DEFAULT 0,
        total_collected NUMERIC(12, 2) DEFAULT 0.00,
        last_billing_date DATE,
        next_billing_date DATE,
        cancellation_reason VARCHAR(255),
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )
    """)
    print("[OK] 'autopay_subscriptions' table verified.")

    # 2. Check and add columns to 'donations' table
    print("Checking 'donations' table columns...")
    cursor.execute("PRAGMA table_info(donations)")
    existing_cols = [row[1] for row in cursor.fetchall()]

    new_donation_cols = [
        ("donor_phone", "VARCHAR(20)"),
        ("donor_pan", "VARCHAR(10)"),
        ("purpose", "VARCHAR(255) DEFAULT 'General Support'"),
        ("donation_type", "VARCHAR(20) DEFAULT 'one_time'"),
        ("gateway", "VARCHAR(50) DEFAULT 'mock_simulator'"),
        ("gateway_order_id", "VARCHAR(100)"),
        ("gateway_payment_id", "VARCHAR(100)"),
        ("gateway_signature", "VARCHAR(255)"),
        ("failure_reason", "TEXT"),
        ("subscription_id", "INTEGER")
    ]

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

    conn.commit()
    conn.close()
    print("[SUCCESS] Database migration for payment gateways & auto-pay completed successfully!")

if __name__ == '__main__':
    run_migration()
