"""
Automated Comprehensive Test Script for Module 8:
Member Professional ID Card & Official Appointment Letter with QR Code Verification.
All code contains proper English comments for clarity and maintenance.
"""

import sys
import os
from datetime import date, datetime

# Ensure project root is in sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from app.extensions import db
from app.models.user import User
from app.models.role import Role
from app.models.appointment_letter import AppointmentLetter
from app.blueprints.staff import generate_qr_code_data_uri
from app.services.notification_service import send_member_id_card_email, send_appointment_letter_email

def run_tests():
    app = create_app()
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['SERVER_NAME'] = 'localhost'

    with app.test_client() as client:
        with app.app_context():
            print("================================================================")
            print("   MODULE 8: MEMBER ID CARD & APPOINTMENT LETTER TEST SUITE     ")
            print("================================================================")

            # 1. TEST USER MODEL PROPERTIES
            print("\n[TEST 1] Testing User model properties for Member ID...")
            admin = User.query.filter_by(email="admin@ngo.org").first()
            assert admin is not None, "Admin user must exist!"
            admin_id = admin.id
            print(f"  * Admin Full Name      : {admin.full_name}")
            print(f"  * Formatted Member ID  : {admin.formatted_member_id}")
            print(f"  * Appointment Ref No   : {admin.appointment_ref_no}")
            print(f"  * Official Designation : {admin.official_designation}")
            print(f"  * Joining Date         : {admin.joining_date_formatted}")
            print(f"  * Validity Expiry      : {admin.validity_date_formatted}")
            assert admin.formatted_member_id.startswith("NGO/MEM/"), "Member ID format should start with NGO/MEM/"
            assert admin.appointment_ref_no.startswith("NGO/APPT/"), "Appointment Ref format should start with NGO/APPT/"
            print("  --> [PASS] User model attributes & properties verified.")

            # 2. TEST QR CODE DATA URI GENERATOR
            print("\n[TEST 2] Testing Base64 QR Code generation...")
            test_qr_url = f"http://127.0.0.1:5000/verify/{admin.formatted_member_id}"
            qr_uri = generate_qr_code_data_uri(test_qr_url)
            assert qr_uri.startswith("data:image/png;base64,"), "QR Code must be a Base64 PNG data URI"
            print(f"  * QR Code URI generated ({len(qr_uri)} characters)")
            print("  --> [PASS] QR Code generation verified.")

            # 3. TEST APPOINTMENT LETTER MODEL CREATION
            print("\n[TEST 3] Testing AppointmentLetter model persistence...")
            appt = AppointmentLetter.query.filter_by(user_id=admin.id).first()
            if not appt:
                appt = AppointmentLetter(
                    reference_no=admin.appointment_ref_no,
                    user_id=admin.id,
                    recipient_name=admin.full_name,
                    recipient_email=admin.email,
                    recipient_phone=admin.phone or "+91 99999 88888",
                    recipient_address=admin.address or "Central Secretariat Hub, New Delhi, India",
                    designation=admin.official_designation,
                    appointment_date=date.today(),
                    effective_date=date.today(),
                    terms_content="1. Uphold core values.\n2. Dedicate scheduled weekly volunteering.",
                    authorized_signatory="Rajkumar Maurya, General Secretary & Trustee",
                    status="active"
                )
                db.session.add(appt)
                db.session.commit()

            print(f"  * Appointment ID       : {appt.id}")
            print(f"  * Reference Number     : {appt.reference_no}")
            print(f"  * Conferred Designation: {appt.designation}")
            print(f"  * Formatted Date       : {appt.formatted_appointment_date}")
            assert appt.reference_no.startswith("NGO/APPT/"), "Appointment reference must start with NGO/APPT/"
            print("  --> [PASS] AppointmentLetter model verified.")

            # 4. TEST EMAIL DISPATCH NOTIFICATION SERVICES
            print("\n[TEST 4] Testing email dispatch services...")
            card_email_sent = send_member_id_card_email(admin, f"http://localhost:5000/verify/{admin.formatted_member_id}")
            assert card_email_sent is True, "send_member_id_card_email must succeed"
            print("  * Member ID Card email dispatched: True")

            appt_email_sent = send_appointment_letter_email(admin, appt, f"http://localhost:5000/verify/{appt.reference_no}")
            assert appt_email_sent is True, "send_appointment_letter_email must succeed"
            print("  * Appointment Letter email dispatched: True")
            print("  --> [PASS] Notification service methods executed successfully.")

        # 5. TEST PUBLIC QR VERIFICATION PORTAL FOR MEMBER ID
        print("\n[TEST 5] Testing Public QR Verification Portal for Member ID...")
        res_mem = client.get(f"/verify/{admin.formatted_member_id}")
        assert res_mem.status_code == 200, f"Expected 200 from public verify, got {res_mem.status_code}"
        html_mem = res_mem.get_data(as_text=True)
        assert "Officially Verified Member" in html_mem, "Public portal must display verified member badge"
        assert admin.full_name in html_mem, "Admin full name must appear on public verification page"
        print(f"  * Public verification for {admin.formatted_member_id} returned 200 with Verified badge.")
        print("  --> [PASS] Public Member ID verification verified.")

        # 6. TEST PUBLIC QR VERIFICATION PORTAL FOR APPOINTMENT LETTER
        print("\n[TEST 6] Testing Public QR Verification Portal for Appointment Letter...")
        res_appt = client.get(f"/verify/{appt.reference_no}")
        assert res_appt.status_code == 200, f"Expected 200 from public verify, got {res_appt.status_code}"
        html_appt = res_appt.get_data(as_text=True)
        assert "Officially Verified Appointment" in html_appt, "Public portal must display verified appointment badge"
        assert appt.recipient_name in html_appt, "Recipient name must appear on appointment verification page"
        print(f"  * Public verification for {appt.reference_no} returned 200 with Verified badge.")
        print("  --> [PASS] Public Appointment Letter verification verified.")

        # 7. TEST ADMIN AUTHENTICATED ROUTES
        print("\n[TEST 7] Testing Admin ID Card & Appointment Letter views...")
        # Authenticate Admin client
        with client.session_transaction() as sess:
            sess['_user_id'] = str(admin_id)
            sess['_fresh'] = True

        # View ID Card
        res_card_view = client.get(f"/admin/members/{admin_id}/id-card")
        assert res_card_view.status_code == 200, f"Expected 200 from id-card view, got {res_card_view.status_code}"
        assert "Member Professional ID Card" in res_card_view.get_data(as_text=True), "ID card view must contain title"
        print(f"  * Admin View ID Card returned 200 OK.")

        # View Appointment Letter
        res_letter_view = client.get(f"/admin/members/{admin_id}/appointment-letter")
        assert res_letter_view.status_code == 200, f"Expected 200 from appointment view, got {res_letter_view.status_code}"
        assert "Official Letter of Appointment" in res_letter_view.get_data(as_text=True), "Appointment letter view must contain title"
        print(f"  * Admin View Appointment Letter returned 200 OK.")

        # Send ID Card via POST
        res_card_send = client.post(f"/admin/members/{admin_id}/send-id-card", follow_redirects=True)
        assert res_card_send.status_code == 200, f"Expected 200 from send-id-card post, got {res_card_send.status_code}"
        print(f"  * Admin Send ID Card POST returned 200 OK with redirect.")

        # Send Appointment Letter via POST
        res_appt_send = client.post(f"/admin/members/{admin_id}/send-appointment", follow_redirects=True)
        assert res_appt_send.status_code == 200, f"Expected 200 from send-appointment post, got {res_appt_send.status_code}"
        print(f"  * Admin Send Appointment POST returned 200 OK with redirect.")

        # 8. TEST MEMBER PORTAL DIRECT ENDPOINTS
        print("\n[TEST 8] Testing Member Portal direct endpoints...")
        res_my_card = client.get("/portal/my-id-card")
        assert res_my_card.status_code == 200, f"Expected 200 from /portal/my-id-card, got {res_my_card.status_code}"
        print(f"  * /portal/my-id-card returned 200 OK.")

        res_my_appt = client.get("/portal/my-appointment")
        assert res_my_appt.status_code == 200, f"Expected 200 from /portal/my-appointment, got {res_my_appt.status_code}"
        print(f"  * /portal/my-appointment returned 200 OK.")

        print("\n================================================================")
        print("   ALL 8 TESTS PASSED SUCCESSFULLY! MODULE 8 IS 100% READY!     ")
        print("================================================================")

if __name__ == '__main__':
    run_tests()
