"""
Test Cases for Domains Page

Tests the domains listing page functionality:
- Page load and rendering
- Domain cards visibility
- Domain IDs extraction
- Domain lock/unlock status
- Start/Continue buttons
- Overall progress tracking
- Navigation to domain assessment
"""
import pytest
from pages.domains_page import DomainsPage
from selenium.webdriver.common.by import By


@pytest.mark.assessment
@pytest.mark.domains_page
class TestDomainsPage:
    """Test cases for Domains Page"""
    
    def test_domains_page_loads(self, assessment_with_domains):
        """Test that domains page loads successfully"""
        domains_page = assessment_with_domains['domains_page']
        driver = assessment_with_domains['driver']
        
        # Verify URL
        assert "/assessment/" in driver.current_url, \
               f"Should be on assessment page. Current URL: {driver.current_url}"
        assert "/domains" in driver.current_url, \
               f"Should be on domains page. Current URL: {driver.current_url}"
        
        # Verify page loaded
        domains_page.wait_for_page_load()
        
        # Verify back button is visible
        assert domains_page.is_element_visible(domains_page.BACK_BUTTON, timeout=5), \
               "Back button should be visible"
        
        print(f"✅ Domains page loaded successfully: {driver.current_url}")
    
    def test_domain_cards_visible(self, assessment_with_domains):
        """Test that domain cards are visible on the page"""
        domains_page = assessment_with_domains['domains_page']
        domain_ids = assessment_with_domains['domain_ids']
        
        assert len(domain_ids) > 0, "At least one domain should be available"
        
        # Verify each domain card is visible
        for domain_id in domain_ids:
            card = domains_page.get_domain_card(domain_id)
            assert card.is_displayed(), f"Domain card {domain_id} should be visible"
            
            # Verify card has data-testid
            test_id = card.get_attribute("data-testid")
            assert test_id == f"domain_card__{domain_id}", \
                   f"Domain card should have correct data-testid. Expected: domain_card__{domain_id}, Got: {test_id}"
        
        print(f"✅ Found {len(domain_ids)} domain card(s) with proper structure")
    
    def test_domain_ids_extraction(self, assessment_with_domains):
        """Test that domain IDs can be extracted correctly"""
        domains_page = assessment_with_domains['domains_page']
        
        # Get domain IDs
        domain_ids = domains_page.get_all_domain_ids()
        
        assert len(domain_ids) > 0, "At least one domain ID should be found"
        
        # Verify IDs are valid (numeric)
        for domain_id in domain_ids:
            assert domain_id.isdigit(), \
                   f"Domain ID should be numeric. Got: {domain_id}"
        
        print(f"✅ Extracted {len(domain_ids)} domain ID(s): {domain_ids}")
    
    def test_domain_lock_status(self, assessment_with_domains):
        """Test domain lock/unlock status checking"""
        domains_page = assessment_with_domains['domains_page']
        domain_ids = assessment_with_domains['domain_ids']
        
        if not domain_ids:
            pytest.skip("No domains available")
        
        # Check lock status for each domain
        for domain_id in domain_ids:
            is_locked = domains_page.is_domain_locked(domain_id)
            is_unlocked = domains_page.is_domain_unlocked(domain_id)
            
            # Lock and unlock should be opposite
            assert is_locked != is_unlocked, \
                   f"Domain {domain_id}: is_locked and is_unlocked should be opposite"
            
            print(f"   Domain {domain_id}: {'🔒 Locked' if is_locked else '🔓 Unlocked'}")
        
        print(f"✅ Domain lock status checked for {len(domain_ids)} domain(s)")
    
    def test_domain_action_button(self, assessment_with_domains):
        """Test that domain action buttons are present and clickable"""
        domains_page = assessment_with_domains['domains_page']
        domain_ids = assessment_with_domains['domain_ids']
        
        if not domain_ids:
            pytest.skip("No domains available")
        
        # Check action button for first domain
        first_domain_id = domain_ids[0]
        action_button = domains_page.driver.find_element(
            By.CSS_SELECTOR,
            f"[data-testid='domain_card__{first_domain_id}_action']"
        )
        
        assert action_button.is_displayed(), \
               f"Action button for domain {first_domain_id} should be visible"
        
        # Get button text (Start/Continue/Resume)
        button_text = action_button.text.strip()
        assert len(button_text) > 0, "Action button should have text"
        
        # Check if button is enabled (unlocked domains should be clickable)
        is_locked = domains_page.is_domain_locked(first_domain_id)
        if not is_locked:
            assert action_button.is_enabled(), \
                   f"Action button for unlocked domain {first_domain_id} should be enabled"
        
        print(f"✅ Domain {first_domain_id} action button verified")
        print(f"   Button text: {button_text}")
        print(f"   Status: {'🔒 Locked' if is_locked else '🔓 Unlocked'}")
    
    def test_overall_progress_tracking(self, assessment_with_domains):
        """Test overall progress value display"""
        domains_page = assessment_with_domains['domains_page']
        
        # Get overall progress
        progress = domains_page.get_overall_progress()
        
        # Progress should be a percentage string (e.g., "0%", "25%", "100%")
        assert "%" in progress or progress.isdigit(), \
               f"Progress should be a percentage. Got: {progress}"
        
        print(f"✅ Overall progress: {progress}")
    
    def test_start_domain_navigation(self, assessment_with_domains):
        """Test that clicking Start Domain navigates to domain assessment"""
        domains_page = assessment_with_domains['domains_page']
        driver = assessment_with_domains['driver']
        domain_ids = assessment_with_domains['domain_ids']
        
        if not domain_ids:
            pytest.skip("No domains available")
        
        # Find first unlocked domain
        unlocked_domain_id = None
        for domain_id in domain_ids:
            if domains_page.is_domain_unlocked(domain_id):
                unlocked_domain_id = domain_id
                break
        
        if not unlocked_domain_id:
            pytest.skip("No unlocked domains available")
        
        # Click Start Domain
        domains_page.click_domain_action(unlocked_domain_id)
        
        # Verify navigation to domain assessment
        assert "/domain/" in driver.current_url, \
               f"Should navigate to domain assessment page. Current URL: {driver.current_url}"
        assert unlocked_domain_id in driver.current_url, \
               f"URL should contain domain ID {unlocked_domain_id}. Current URL: {driver.current_url}"
        
        print(f"✅ Successfully navigated to domain assessment for domain {unlocked_domain_id}")
        print(f"   URL: {driver.current_url}")
    
    def test_back_button_navigation(self, assessment_with_domains):
        """Test that back button returns to assessments page"""
        domains_page = assessment_with_domains['domains_page']
        driver = assessment_with_domains['driver']
        
        # Click back button
        domains_page.click_back()
        
        # Verify navigation to assessments page
        assert "/assessments" in driver.current_url, \
               f"Should navigate back to assessments page. Current URL: {driver.current_url}"
        
        print(f"✅ Back button navigated to assessments page: {driver.current_url}")






