#!/usr/bin/env python3
"""
Quick DOM Check - Verify current DOM state
"""
import sys
from pathlib import Path
import json
import time

project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from selenium.webdriver.common.by import By
from pages.login_page import LoginPage
from pages.mandatory_reset_page import MandatoryResetPage
from pages.profile_editor_page import ProfileEditorPage
from utils.driver_manager import DriverManager
from config.config import TEST_NEW_PASSWORD, BASE_URL


def get_all_data_testids(driver):
    """Get all data-testid attributes from DOM"""
    elements = driver.find_elements(By.CSS_SELECTOR, "[data-testid]")
    testids = {}
    for elem in elements:
        testid = elem.get_attribute("data-testid")
        if testid:
            testids[testid] = {
                "tag": elem.tag_name,
                "visible": elem.is_displayed(),
                "text": elem.text[:50] if elem.text else ""
            }
    return testids


def main():
    driver = None
    try:
        print("🚀 Quick DOM Verification")
        print(f"🌐 {BASE_URL}\n")
        
        driver_manager = DriverManager()
        driver = driver_manager.get_driver(headless=False)
        
        # Login
        print("📝 Logging in...")
        login_page = LoginPage(driver)
        login_page.login(identifier="BARBAR110A", password="jKSQDny@8C4r")
        time.sleep(2)
        
        # Handle password reset
        reset_page = MandatoryResetPage(driver)
        if reset_page.is_modal_present():
            print("🔄 Resetting password...")
            reset_page.reset_password("jKSQDny@8C4r", TEST_NEW_PASSWORD, TEST_NEW_PASSWORD, "BARBAR110A")
            time.sleep(2)
        
        # Navigate to profile editor
        print("📝 Navigating to profile editor...")
        profile_editor = ProfileEditorPage(driver)
        profile_editor.navigate()
        time.sleep(3)
        
        # Get all testids
        print("\n🔍 Extracting all data-testid attributes from DOM...")
        all_testids = get_all_data_testids(driver)
        
        print(f"\n✅ Found {len(all_testids)} elements with data-testid attributes\n")
        
        # Group by scope
        scopes = {}
        for testid in all_testids:
            scope = testid.split("__")[0] if "__" in testid else "unknown"
            if scope not in scopes:
                scopes[scope] = []
            scopes[scope].append(testid)
        
        print("📊 Breakdown by scope:")
        for scope, testids in sorted(scopes.items()):
            print(f"   {scope}: {len(testids)} attributes")
        
        # Check profile_editor specifically
        profile_testids = [tid for tid in all_testids if tid.startswith("profile_editor__")]
        print(f"\n📊 Profile Editor: {len(profile_testids)} attributes found")
        
        if profile_testids:
            print("\n✅ Profile Editor attributes found:")
            for tid in sorted(profile_testids)[:30]:
                print(f"   - {tid}")
            if len(profile_testids) > 30:
                print(f"   ... and {len(profile_testids) - 30} more")
        else:
            print("\n❌ NO profile_editor attributes found!")
        
        # Check for specific patterns
        print("\n🔍 Checking specific patterns...")
        patterns = {
            "Tabs": [tid for tid in profile_testids if "tab_" in tid],
            "Inputs": [tid for tid in profile_testids if "_input" in tid],
            "Selects": [tid for tid in profile_testids if "_select" in tid],
            "Textareas": [tid for tid in profile_testids if "_textarea" in tid],
            "Buttons": [tid for tid in profile_testids if "_button" in tid],
            "Checkboxes (Focus)": [tid for tid in profile_testids if "focus__" in tid],
            "Checkboxes (Strength)": [tid for tid in profile_testids if "strength__" in tid],
            "Checkboxes (Hobby)": [tid for tid in profile_testids if "hobby__" in tid],
            "Checkboxes (Club)": [tid for tid in profile_testids if "club_" in tid],
            "Checkboxes (Expectation)": [tid for tid in profile_testids if "expectation__" in tid],
        }
        
        for name, matching in patterns.items():
            if matching:
                print(f"   ✅ {name}: {len(matching)} found")
            else:
                print(f"   ❌ {name}: 0 found")
        
        # Save results
        results = {
            "total_found": len(all_testids),
            "profile_editor_count": len(profile_testids),
            "all_testids": list(all_testids.keys()),
            "profile_editor_testids": profile_testids,
            "by_scope": {scope: len(testids) for scope, testids in scopes.items()},
            "patterns": {name: len(matching) for name, matching in patterns.items()}
        }
        
        results_file = project_root / "analysis" / "quick_dom_check_results.json"
        with open(results_file, 'w') as f:
            json.dump(results, f, indent=2)
        
        print(f"\n📄 Results saved to: {results_file}")
        print("\n⏸️  Browser open for 60 seconds...")
        time.sleep(60)
        
    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
    finally:
        if driver:
            driver.quit()


if __name__ == "__main__":
    main()






