"""
Automated Smoke Test for Payment Gateways & Auto-Pay Recurring Donation.
Tests:
1. Public Donate Page loads gateway config.
2. Initiates One-Time Online Donation Checkout.
3. Simulates Successful Payment via Mock Sandbox Gateway.
4. Checks 80G Tax Exemption Receipt generation and scannable QR verification.
5. Initiates Monthly Auto-Pay Recurring Subscription Checkout.
6. Simulates Recurring Mandate activation.
7. Executes Batch Auto-Debit Scheduler engine.
8. Tests Donor Subscription Portal (Pause, Resume, Cancel).
9. Tests Admin Gateways Switcher & Ledger.
"""

import sys
import os

# Add root directory to sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from app import create_app, db
from app.models.donation import Donation
from app.models.autopay_subscription import AutoPaySubscription
from app.models.donation_receipt import DonationReceipt
from app.models.user import User
from app.services.payment_service import (
    get_payment_gateway_config,
    save_payment_gateway_config,
    initiate_donation_checkout,
    settle_successful_donation,
    execute_due_recurring_subscriptions,
    update_subscription_status
)

def run_smoke_test():
    app = create_app()
    client = app.test_client()

    with app.app_context():
        print("=" * 60)
        print("RUNNING PAYMENT GATEWAY & AUTO-PAY SMOKE TEST")
        print("=" * 60)

        # 1. Test Gateway Config retrieval & switching
        config = get_payment_gateway_config()
        print(f"[OK] Current Gateway: {config.get('active_gateway')} (Sandbox: {config.get('sandbox_mode')})")

        # 2. Test One-Time Donation Checkout Initiation
        resp = client.post('/payments/initiate', json={
            'donor_name': 'Ramesh Kumar',
            'donor_email': 'ramesh@example.com',
            'donor_phone': '9876543210',
            'donor_pan': 'ABCDE1234F',
            'amount': 2500,
            'donation_type': 'one_time',
            'purpose': 'Education for Underprivileged Children'
        })
        assert resp.status_code == 200, f"Initiate failed: {resp.data}"
        init_data = resp.get_json()
        assert init_data['success'] is True
        tx_id = init_data['transaction_id']
        print(f"[OK] One-Time Donation initiated: TxID = {tx_id}")

        # 3. Simulate Successful Payment via Mock Sandbox
        sim_resp = client.post('/payments/simulate', json={
            'transaction_id': tx_id,
            'action': 'success'
        })
        assert sim_resp.status_code == 200, f"Simulate failed: {sim_resp.data}"
        sim_data = sim_resp.get_json()
        assert sim_data['success'] is True
        print(f"[OK] Payment Simulated Successfully: Redirect = {sim_data['redirect_url']}")

        # 4. Verify Database State & 80G Receipt
        donation = Donation.query.filter_by(transaction_id=tx_id).first()
        assert donation is not None
        assert donation.status == 'success'
        receipt = DonationReceipt.query.filter_by(donation_id=donation.id).first()
        assert receipt is not None
        print(f"[OK] 80G Tax Receipt Generated: Receipt No = {receipt.receipt_no}")
        print(f"     Amount in words: {receipt.amount_in_words()}")

        # 5. Test Monthly Auto-Pay Recurring Subscription Initiation
        resp_rec = client.post('/payments/initiate', json={
            'donor_name': 'Pooja Sharma',
            'donor_email': 'pooja@example.com',
            'donor_phone': '9123456789',
            'donor_pan': 'XYZPK9876L',
            'amount': 1000,
            'donation_type': 'recurring',
            'billing_day': 5,
            'purpose': 'Monthly Mid-Day Meals'
        })
        assert resp_rec.status_code == 200
        rec_init_data = resp_rec.get_json()
        rec_tx_id = rec_init_data['transaction_id']
        print(f"[OK] Monthly Auto-Pay Mandate initiated: TxID = {rec_tx_id}")

        # 6. Simulate Successful Auto-Pay Setup
        sim_rec_resp = client.post('/payments/simulate', json={
            'transaction_id': rec_tx_id,
            'action': 'success'
        })
        assert sim_rec_resp.status_code == 200
        
        # Verify AutoPaySubscription created
        sub = AutoPaySubscription.query.filter_by(donor_email='pooja@example.com').first()
        assert sub is not None
        assert sub.status == 'active'
        assert sub.billing_day == 5
        print(f"[OK] Auto-Pay Mandate Active: Code = {sub.mandate_code}, Next Billing = {sub.next_billing_date}")

        # 7. Test Batch Auto-Debit Execution
        batch_result = execute_due_recurring_subscriptions()
        print(f"[OK] Batch Auto-Debit Engine executed: Total Due = {batch_result['total_due']}, Success = {batch_result['processed_success']}")

        # 8. Test Donor Portal status update (Pause -> Resume -> Cancel)
        success_pause, msg_pause = update_subscription_status(sub.mandate_code, 'paused', actor_email='pooja@example.com', reason='Donor requested temporary pause')
        assert success_pause is True
        db.session.refresh(sub)
        assert sub.status == 'paused'
        print(f"[OK] Donor Portal Pause Mandate: Status = {sub.status}")

        success_resume, msg_resume = update_subscription_status(sub.mandate_code, 'active', actor_email='pooja@example.com')
        assert success_resume is True
        db.session.refresh(sub)
        assert sub.status == 'active'
        print(f"[OK] Donor Portal Resume Mandate: Status = {sub.status}")

        # 9. Test Cashfree Payments Gateway Integration
        print("-" * 60)
        print("TESTING CASHFREE PAYMENTS GATEWAY INTEGRATION")
        save_payment_gateway_config({
            'active_gateway': 'cashfree',
            'cashfree_app_id': 'TEST_CF_1098234',
            'cashfree_secret_key': 'cfsk_ma_test_90184294829',
            'cashfree_api_version': '2023-08-01'
        })
        cf_cfg = get_payment_gateway_config()
        assert cf_cfg['active_gateway'] == 'cashfree'
        assert cf_cfg['cashfree_app_id'] == 'TEST_CF_1098234'
        print("[OK] Cashfree Gateway configuration saved & verified.")

        cf_resp = client.post('/payments/initiate', json={
            'donor_name': 'Amit Verma',
            'donor_email': 'amit.verma@example.com',
            'donor_phone': '9811223344',
            'donor_pan': 'ABCDE9999Z',
            'amount': 3000,
            'donation_type': 'one_time',
            'purpose': 'Rural Health Mission'
        })
        assert cf_resp.status_code == 200
        cf_init = cf_resp.get_json()
        assert cf_init['gateway'] == 'cashfree'
        assert 'payment_session_id' in cf_init
        cf_tx_id = cf_init['transaction_id']
        print(f"[OK] Cashfree Checkout initiated: TxID = {cf_tx_id}, Session = {cf_init['payment_session_id']}")

        # Test Cashfree return redirect callback
        cf_ret_resp = client.get(f'/payments/cashfree/return?order_id={cf_tx_id}')
        assert cf_ret_resp.status_code == 302
        assert f'/donation/success/{cf_tx_id}' in cf_ret_resp.location
        print(f"[OK] Cashfree Return Callback verified: Redirected to {cf_ret_resp.location}")

        cf_don = Donation.query.filter_by(transaction_id=cf_tx_id).first()
        assert cf_don.status == 'success'
        assert cf_don.gateway == 'cashfree'
        print(f"[OK] Cashfree Payment settled in database! Status: {cf_don.status}")

        # Restore gateway back to mock_simulator for default demo
        save_payment_gateway_config({'active_gateway': 'mock_simulator'})
        print("[OK] Reset active gateway back to mock_simulator for demo.")

        print("=" * 60)
        print("ALL TESTS (INCLUDING CASHFREE) COMPLETED SUCCESSFULLY! ZERO ERRORS.")
        print("=" * 60)

if __name__ == '__main__':
    run_smoke_test()
