"""
Assessments Page Object Model

Handles assessment hub/product page.
Scope: assessment_card
"""
from selenium.webdriver.common.by import By
from pages.base_page import BasePage
from config.config import ASSESSMENTS_URL


class AssessmentsPage(BasePage):
    """Page Object for Assessments Page"""
    
    # Locators using data-testid (scope: assessment_card)
    # Dynamic pattern: assessment_card__{assignmentId} and assessment_card__{assignmentId}_action
    
    def __init__(self, driver):
        """Initialize Assessments Page"""
        super().__init__(driver)
        self.url = ASSESSMENTS_URL
    
    def navigate(self):
        """Navigate to assessments page"""
        self.navigate_to(self.url)
    
    def wait_for_page_load(self):
        """Wait for assessments page to load completely"""
        super().wait_for_page_load()  # Call parent method
    
    def get_assessment_card(self, assignment_id):
        """
        Get assessment card element by assignment ID
        
        Args:
            assignment_id: Assignment/Assessment ID
            
        Returns:
            WebElement: Assessment card element
        """
        card_locator = (By.CSS_SELECTOR, f"[data-testid='assessment_card__{assignment_id}']")
        return self.find_element(card_locator)
    
    def click_begin_assessment(self, assignment_id):
        """
        Click Begin/Continue/Resume button for an assessment
        
        Args:
            assignment_id: Assignment/Assessment ID
        """
        action_locator = (By.CSS_SELECTOR, f"[data-testid='assessment_card__{assignment_id}__action']")
        self.click_element(action_locator)
        # Wait for navigation to domains page
        self.wait.wait_for_url_contains("/assessment/")
        self.wait.wait_for_url_contains("/domains")
    
    def get_all_assessment_cards(self):
        """
        Get all assessment cards on the page
        
        Returns:
            list: List of assessment card elements
        """
        # Find all elements with assessment_card pattern
        cards = self.driver.find_elements(By.CSS_SELECTOR, "[data-testid^='assessment_card__']")
        return cards
    
    def get_assessment_ids(self):
        """
        Get all assessment IDs from cards on the page
        
        Returns:
            list: List of assessment IDs
        """
        import re
        cards = self.get_all_assessment_cards()
        ids = []
        for card in cards:
            test_id = card.get_attribute("data-testid")
            if test_id:
                # Extract ID from pattern: assessment_card__{id} or assessment_card__{id}_action
                match = re.search(r'assessment_card__(\d+)', test_id)
                if match:
                    ids.append(match.group(1))
        return list(set(ids))  # Return unique IDs
