"""
Comprehensive Legal Documents Integration Tests
Tests all aspects of legal document integration including routes, embeds, downloads, and UI elements.
"""

import os
import pytest
from bs4 import BeautifulSoup


class TestLegalDocsIntegration:
    """Test legal documents integration E2E"""

    @pytest.fixture
    def app(self):
        """Create Flask app instance for testing"""
        from app import create_app
        app = create_app()
        app.config.update({
            "TESTING": True,
            "WTF_CSRF_ENABLED": False,  # Disable CSRF for testing
            "SECRET_KEY": "test-secret-key"
        })
        return app

    @pytest.fixture
    def client(self, app):
        """Create test client"""
        return app.test_client()

    def test_static_files_existence(self):
        """Test that all required legal PDF files exist"""
        required_files = [
            'terms_of_service.pdf',
            'privacy_policy.pdf', 
            'dispute_resolution.pdf',
            'ica_template.pdf',
            'safety_guidelines.pdf',
            'payment_terms.pdf'
        ]
        
        missing_files = []
        for file_name in required_files:
            file_path = os.path.join('app', 'static', 'legal', file_name)
            if not os.path.exists(file_path):
                missing_files.append(file_name)
        
        assert not missing_files, f"Missing legal PDF files: {missing_files}"

    def test_legal_terms_route(self, client):
        """Test /legal/terms route renders with PDF embed and download"""
        response = client.get('/legal/terms')
        assert response.status_code == 200
        
        html = response.data.decode('utf-8')
        # Check for PDF embed object
        assert '<object' in html.lower()
        # Check for correct PDF path
        assert 'legal/terms_of_service.pdf' in html
        # Check for download link
        assert 'Download' in html and 'legal/terms_of_service.pdf' in html

    def test_legal_privacy_route(self, client):
        """Test /legal/privacy route renders with PDF embed and download"""
        response = client.get('/legal/privacy')
        assert response.status_code == 200
        
        html = response.data.decode('utf-8')
        # Check for PDF embed object
        assert '<object' in html.lower()
        # Check for correct PDF path
        assert 'legal/privacy_policy.pdf' in html
        # Check for download link
        assert 'Download' in html and 'legal/privacy_policy.pdf' in html

    def test_legal_disputes_route(self, client):
        """Test /legal/disputes route renders with PDF embed and download"""
        response = client.get('/legal/disputes')
        assert response.status_code == 200
        
        html = response.data.decode('utf-8')
        # Check for PDF embed object
        assert '<object' in html.lower()
        # Check for correct PDF path
        assert 'legal/dispute_resolution.pdf' in html
        # Check for download link
        assert 'Download' in html and 'legal/dispute_resolution.pdf' in html

    def test_legal_ica_template_route(self, client):
        """Test /legal/ica_template route renders with PDF embed and download"""
        response = client.get('/legal/ica_template')
        assert response.status_code == 200
        
        html = response.data.decode('utf-8')
        # Check for PDF embed object
        assert '<object' in html.lower()
        # Check for correct PDF path
        assert 'legal/ica_template.pdf' in html
        # Check for download link
        assert 'Download' in html and 'legal/ica_template.pdf' in html

    def test_legal_safety_guidelines_route(self, client):
        """Test /legal/safety route renders with PDF embed and download"""
        response = client.get('/legal/safety')
        assert response.status_code == 200
        
        html = response.data.decode('utf-8')
        # Check for PDF embed object
        assert '<object' in html.lower()
        # Check for correct PDF path
        assert 'legal/safety_guidelines.pdf' in html
        # Check for download link  
        assert 'Download' in html and 'legal/safety_guidelines.pdf' in html

    def test_legal_payment_terms_route(self, client):
        """Test /legal/payment_terms route renders with PDF embed and download"""
        response = client.get('/legal/payment_terms')
        assert response.status_code == 200
        
        html = response.data.decode('utf-8')
        # Check for PDF embed object
        assert '<object' in html.lower()
        # Check for correct PDF path
        assert 'legal/payment_terms.pdf' in html
        # Check for download link
        assert 'Download' in html and 'legal/payment_terms.pdf' in html

    def test_footer_legal_links(self, client, app):
        """Test that footer contains all legal document links"""
        # Use a public page that extends base.html to test footer
        # Try home page first, then fallback to legal route if needed
        try:
            response = client.get('/')
            if response.status_code != 200:
                # Fallback to a known working legal route
                response = client.get('/legal/terms')
        except:
            # Fallback to legal route
            response = client.get('/legal/terms')
            
        assert response.status_code == 200
        
        html = response.data.decode('utf-8')
        soup = BeautifulSoup(html, 'html.parser')
        
        # Test URLs are generated correctly using url_for
        with app.app_context():
            from flask import url_for
            
            expected_urls = {
                'terms': url_for('legal.terms'),
                'privacy': url_for('legal.privacy'), 
                'payment_terms': url_for('legal.payment_terms'),
                'disputes': url_for('legal.disputes'),
                'safety': url_for('legal.safety'),
                'ica_template': url_for('legal.ica_template')
            }
            
            # Check that footer contains these URLs
            footer = soup.find('footer')
            assert footer is not None, "Footer not found in page"
            
            footer_html = str(footer)
            missing_links = []
            for link_name, expected_url in expected_urls.items():
                if expected_url not in footer_html:
                    missing_links.append(f"{link_name}: {expected_url}")
            
            assert not missing_links, f"Missing footer links: {missing_links}"

    def test_signup_page_terms_checkbox(self, client):
        """Test registration page contains T&C checkbox with legal links"""
        response = client.get('/register')
        assert response.status_code == 200
        
        html = response.data.decode('utf-8')
        soup = BeautifulSoup(html, 'html.parser')
        
        # Check for accept_terms checkbox
        checkbox = soup.find('input', {'name': 'accept_terms', 'type': 'checkbox'})
        assert checkbox is not None, "accept_terms checkbox not found"
        
        # Check for links to legal.terms and legal.privacy in the checkbox label
        checkbox_label = soup.find('label', {'for': 'accept_terms'})
        assert checkbox_label is not None, "Terms checkbox label not found"
        
        label_html = str(checkbox_label)
        
        # Check for links to terms and privacy
        assert 'legal.terms' in label_html or '/legal/terms' in label_html, "Terms of Service link missing in checkbox"
        assert 'legal.privacy' in label_html or '/legal/privacy' in label_html, "Privacy Policy link missing in checkbox"

    def test_all_routes_return_200(self, client):
        """Test all legal routes return successful status codes"""
        routes_to_test = [
            '/legal/terms',
            '/legal/privacy', 
            '/legal/disputes',
            '/legal/ica_template',
            '/legal/safety',
            '/legal/payment_terms'
        ]
        
        failed_routes = []
        for route in routes_to_test:
            try:
                response = client.get(route)
                if response.status_code != 200:
                    failed_routes.append(f"{route}: {response.status_code}")
            except Exception as e:
                failed_routes.append(f"{route}: Exception - {str(e)}")
        
        assert not failed_routes, f"Failed routes: {failed_routes}"

    def test_legal_template_structure(self, client):
        """Test that legal templates contain required HTML structure"""
        routes_and_files = [
            ('/legal/terms', 'terms_of_service.pdf'),
            ('/legal/privacy', 'privacy_policy.pdf'),
            ('/legal/disputes', 'dispute_resolution.pdf'), 
            ('/legal/ica_template', 'ica_template.pdf'),
            ('/legal/safety', 'safety_guidelines.pdf'),
            ('/legal/payment_terms', 'payment_terms.pdf')
        ]
        
        for route, pdf_file in routes_and_files:
            response = client.get(route)
            assert response.status_code == 200
            
            html = response.data.decode('utf-8')
            soup = BeautifulSoup(html, 'html.parser')
            
            # Check for page title
            title = soup.find('title')
            assert title is not None, f"No title found for {route}"
            
            # Check for PDF object embed
            pdf_object = soup.find('object')
            assert pdf_object is not None, f"No PDF object found for {route}"
            
            # Check object has correct type
            object_type = pdf_object.get('type')
            assert object_type == 'application/pdf', f"Incorrect object type for {route}: {object_type}"
            
            # Check object data attribute points to correct PDF
            object_data = pdf_object.get('data')
            assert pdf_file in object_data, f"Object data doesn't reference {pdf_file} for {route}"
            
            # Check for download link
            download_links = soup.find_all('a', href=True)
            download_found = False
            for link in download_links:
                if pdf_file in link['href'] and ('download' in link.get('class', []) or 'Download' in link.text):
                    download_found = True
                    break
            assert download_found, f"Download link not found for {route}"

    def test_static_file_routes(self, client):
        """Test that static PDF files are accessible directly"""
        pdf_files = [
            'terms_of_service.pdf',
            'privacy_policy.pdf',
            'dispute_resolution.pdf', 
            'ica_template.pdf',
            'safety_guidelines.pdf',
            'payment_terms.pdf'
        ]
        
        failed_static_files = []
        for pdf_file in pdf_files:
            try:
                static_url = f'/static/legal/{pdf_file}'
                response = client.get(static_url)
                if response.status_code != 200:
                    failed_static_files.append(f"{pdf_file}: {response.status_code}")
            except Exception as e:
                failed_static_files.append(f"{pdf_file}: Exception - {str(e)}")
        
        assert not failed_static_files, f"Failed static file access: {failed_static_files}"


def test_legal_integration_comprehensive():
    """Comprehensive test runner for manual execution"""
    import sys
    sys.path.append('.')
    
    # Test static files
    required_files = [
        'app/static/legal/terms_of_service.pdf',
        'app/static/legal/privacy_policy.pdf',
        'app/static/legal/dispute_resolution.pdf',
        'app/static/legal/ica_template.pdf',
        'app/static/legal/safety_guidelines.pdf', 
        'app/static/legal/payment_terms.pdf'
    ]
    
    print("=== LEGAL DOCS INTEGRATION TEST ===")
    print("\n1. Testing Static Files Existence:")
    for file_path in required_files:
        exists = os.path.exists(file_path)
        status = "✓ EXISTS" if exists else "✗ MISSING"
        print(f"  {file_path}: {status}")
    
    print("\n2. Testing Flask App Creation:")
    try:
        from app import create_app
        app = create_app()
        print("  ✓ create_app() works")
    except Exception as e:
        print(f"  ✗ create_app() failed: {e}")
        return
    
    print("\n3. Testing Legal Routes:")
    with app.test_client() as client:
        routes = [
            '/legal/terms',
            '/legal/privacy',
            '/legal/disputes', 
            '/legal/ica_template',
            '/legal/safety',
            '/legal/payment_terms'
        ]
        
        for route in routes:
            try:
                response = client.get(route)
                status = f"✓ {response.status_code}" if response.status_code == 200 else f"✗ {response.status_code}"
                print(f"  {route}: {status}")
            except Exception as e:
                print(f"  {route}: ✗ Exception - {e}")
    
    print("\n4. Testing Registration Page:")
    try:
        with app.test_client() as client:
            response = client.get('/register')
            if response.status_code == 200:
                html = response.data.decode('utf-8')
                has_checkbox = 'name="accept_terms"' in html
                has_terms_link = 'legal.terms' in html or '/legal/terms' in html
                has_privacy_link = 'legal.privacy' in html or '/legal/privacy' in html
                
                print(f"  Registration page: ✓ {response.status_code}")
                print(f"  T&C checkbox: {'✓' if has_checkbox else '✗'}")
                print(f"  Terms link: {'✓' if has_terms_link else '✗'}")
                print(f"  Privacy link: {'✓' if has_privacy_link else '✗'}")
            else:
                print(f"  Registration page: ✗ {response.status_code}")
    except Exception as e:
        print(f"  Registration page: ✗ Exception - {e}")


if __name__ == '__main__':
    test_legal_integration_comprehensive()
