"""
Live Site Verification Script for NGO Foundation.
Simulates real browser sessions for all roles against the live SQLite database (instance/ngo.db).
Verifies:
1. Role-based authentication (Admin, Verifier, Finance, Volunteer) with CSRF tokens.
2. Correct role-based dashboard landing and template rendering.
3. All public pages (Home, Pillars, Leadership, Ground Workers, Gallery, Jobs, About, Contact, Need-Support, Volunteer, Application-Status, Donate).
4. Admin management sub-pages (Applications, Content, Jobs, Staff, Media).
Fulfills SRS Checklist item C11 (System Health & End-to-End Testing).
"""

import os
import re
import sys

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

from app import create_app
from app.config import Config


class LiveVerificationConfig(Config):
    """Configuration for live verification: uses ngo.db but disables rate limits for verification suite."""
    RATELIMIT_ENABLED = False
    WTF_CSRF_ENABLED = True


def verify_live_site():
    """Executes end-to-end portal and public page verification."""
    app = create_app(LiveVerificationConfig)

    roles_credentials = [
        ('admin@ngo.org', 'admin123', ['/admin/dashboard', '/admin']),
        ('verifier@ngo.org', 'verifier123', ['/verifier/dashboard', '/verifier']),
        ('finance@ngo.org', 'finance123', ['/finance/dashboard', '/finance']),
        ('volunteer@ngo.org', 'volunteer123', ['/volunteer/dashboard']),
    ]

    print("==================================================")
    print("STARTING LIVE PORTAL & AUTHENTICATION VERIFICATION")
    print("==================================================")

    for email, pwd, expected_landing in roles_credentials:
        with app.test_client() as client:
            # 1. Fetch login page to extract CSRF token
            get_res = client.get('/login')
            assert get_res.status_code == 200, f"GET /login failed with status {get_res.status_code}"

            html = get_res.get_data(as_text=True)
            match = re.search(r'name=["\']csrf_token["\'] value=["\']([^"\']+)["\']', html)
            assert match, "CSRF token not found in login form"
            csrf_token = match.group(1)

            # 2. Submit credentials
            post_res = client.post(
                '/login',
                data={'email': email, 'password': pwd, 'csrf_token': csrf_token},
                follow_redirects=True,
            )
            assert post_res.status_code == 200, f"POST /login for {email} failed with status {post_res.status_code}"
            actual_path = post_res.request.path
            print(f"[AUTH OK] {email:20} -> Landed on {actual_path}")
            assert actual_path in expected_landing, f"Redirect mismatch: got {actual_path}, expected one of {expected_landing}"

            # 3. Test portal dashboard rendering without template errors
            portal_html = post_res.get_data(as_text=True)
            assert "dashboard" in portal_html.lower(), f"Dashboard text missing from {actual_path}"
            print(f"[PAGE OK] {actual_path:20} -> Rendered successfully.")

            # If admin, test admin sub-pages inside this authenticated session
            if email == 'admin@ngo.org':
                print("\n--- CHECKING ADMIN SUB-PAGES ---")
                admin_routes = [
                    '/admin/applications',
                    '/admin/content',
                    '/admin/jobs',
                    '/admin/staff',
                    '/admin/media',
                    '/admin/videos',
                    '/admin/banners',
                ]
                for ar in admin_routes:
                    sub_res = client.get(ar)
                    assert sub_res.status_code == 200, f"Admin sub-page {ar} returned status {sub_res.status_code}"
                    print(f"[ADMIN SUBPAGE OK] {ar:25} -> 200 OK")

    # 4. Check all public pages
    print("\n--- CHECKING PUBLIC PAGES ---")
    public_routes = [
        ('/', 'NGO Foundation'),
        ('/pillars', 'Pillars'),
        ('/leadership', 'Leadership'),
        ('/ground-workers', 'Ground Workforce'),
        ('/gallery', 'Gallery'),
        ('/jobs', 'Jobs'),
        ('/about', 'About'),
        ('/contact', 'Contact'),
        ('/need-support', 'Need Support'),
        ('/volunteer', 'Volunteer with us'),
        ('/application-status', 'Check application status'),
        ('/donate', 'Donate'),
        ('/verify/VOL-B07BFC5D', 'Officially Verified'),
        ('/verify', 'Credential Verification'),
    ]

    with app.test_client() as public_client:
        for route, keyword in public_routes:
            res = public_client.get(route)
            assert res.status_code == 200, f"Route {route} returned status {res.status_code}"
            assert keyword.lower() in res.get_data(as_text=True).lower(), f"Keyword '{keyword}' not found in {route}"
            print(f"[PUBLIC OK] {route:25} -> 200 OK (Contains '{keyword}')")

    print("\n==================================================")
    print("ALL LIVE PORTALS, PUBLIC PAGES & SUB-PAGES 100% OK")
    print("==================================================")
    return True


if __name__ == '__main__':
    verify_live_site()
