import asyncio
from playwright.async_api import async_playwright
from PySide6.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget, QMessageBox
from qasync import QEventLoop
import sys

class CategoryHandler:
    def __init__(self, page):
        self.page = page

    async def handle_category_action(self):
        # #productMainContentContainerId 내부에서 클래스 이름 "ant-select ant-select-outlined css-1li46mu ant-select-single ant-select-show-arrow"를 포함한 요소 중 두 번째 요소 찾기
        print("[DEBUG] handle_category_action: Locating category container element...")
        # category_locator = "div#productMainContentContainerId div.ant-select.ant-select-outlined.css-1li46mu.ant-select-single.ant-select-show-arrow >> nth=0"
        category_locator = "#productMainContentContainerId .ant-select.ant-select-outlined.css-1li46mu.ant-select-single.ant-select-show-arrow:nth-of-type(1)"

        try:
            await self.page.wait_for_selector(category_locator, timeout=5000)
        except Exception as e:
            print(f"[ERROR] handle_category_action: Timed out waiting for category container element. Error: {e}")
            QMessageBox.information(None, "결과", f"카테고리 컨테이너 요소를 찾는 데 실패했습니다: {e}")
            return

        category_element = self.page.locator(category_locator)
        count = await category_element.count()
        print(f"[DEBUG] handle_category_action: Number of elements found with locator '{category_locator}': {count}")
        if count == 0:
            print(f"[ERROR] handle_category_action: Category container element not found using locator '{category_locator}'!")
            QMessageBox.information(None, "결과", "카테고리 컨테이너 요소를 찾을 수 없습니다.")
            return

        # "인증필요"와 카테고리 텍스트 추출
        print("[DEBUG] handle_category_action: Extracting '인증필요' and category text...")
        certification_text = ""
        category_text = ""

        try:
            cert_needed_locator = category_element.locator("div.ant-col.css-1li46mu:nth-child(1)")
            certification_text = await cert_needed_locator.inner_text()
            print(f"[DEBUG] handle_category_action: Certification text found - '{certification_text}'")
            if "인증필요" in certification_text:
                # 인증필요가 있는 경우 두 번째 요소가 카테고리 텍스트
                category_text_locator = category_element.locator("div.ant-col.css-1li46mu:nth-child(2)")
                category_text = await category_text_locator.inner_text()
            else:
                # 인증필요가 없는 경우 첫 번째 요소가 카테고리 텍스트
                category_text = certification_text
                certification_text = ""  # 인증필요가 없으므로 초기화
        except Exception:
            # 인증필요가 없는 경우 첫 번째 요소가 카테고리 텍스트
            print("[DEBUG] handle_category_action: Certification text not found. Assuming first element is category text.")
            category_text_locator = category_element.locator("div.ant-col.css-1li46mu:nth-child(1)")
            category_text = await category_text_locator.inner_text()

        full_text = f"{certification_text} {category_text}".strip()
        print(f"[DEBUG] handle_category_action: Full text - '{full_text}'")
        QMessageBox.information(None, "검색 결과", f"카테고리 텍스트: {full_text}")

        # 카테고리 텍스트에 '인증'이라는 단어가 포함되어 있는지 검사
        if "인증" in full_text:
            print("[INFO] 인증 필요 카테고리입니다. 인증 절차를 진행합니다.")
            # 인증이 필요한 경우 수행할 작업
            await self.perform_certification_action()
        else:
            print("[INFO] 인증이 필요하지 않은 카테고리입니다.")
            # 인증이 필요하지 않은 경우 수행할 작업
            await self.perform_standard_action()

    async def perform_certification_action(self):
        # 인증 절차를 진행하는 코드 작성
        print("[DEBUG] perform_certification_action: Starting certification process...")
        # 예시: 특정 버튼 클릭하기
        await self.page.click("button:has-text('인증 시작')")
        print("[INFO] perform_certification_action: Certification process completed.")

    async def perform_standard_action(self):
        # 인증이 필요하지 않은 경우의 일반적인 작업 코드 작성
        print("[DEBUG] perform_standard_action: Performing standard action...")
        # 예시: 다음 단계로 이동
        await self.page.click("button:has-text('다음 단계')")
        print("[INFO] perform_standard_action: Standard action completed.")

async def run_playwright():
    print("[DEBUG] run_playwright: Launching Playwright...")
    playwright = await async_playwright().start()
    browser = await playwright.chromium.launch(headless=False)
    page = await browser.new_page()
    print("[DEBUG] run_playwright: Navigating to https://www.percenty.co.kr...")
    await page.goto("https://www.percenty.co.kr")  # 실제 페이지 URL로 변경하세요
    print("[INFO] run_playwright: Page loaded successfully.")
    return page, browser, playwright

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Playwright 테스트")
        self.setGeometry(100, 100, 400, 300)
        self.page = None
        self.browser = None
        self.playwright = None

        # 버튼 생성
        self.init_button = QPushButton("Playwright 실행")
        self.init_button.clicked.connect(self.run_playwright_button)

        self.check_button = QPushButton("요소 검사 및 메시지 출력")
        self.check_button.clicked.connect(self.check_category_button)
        self.check_button.setEnabled(False)

        # 레이아웃 설정
        layout = QVBoxLayout()
        layout.addWidget(self.init_button)
        layout.addWidget(self.check_button)
        self.setLayout(layout)

    def run_playwright_button(self):
        print("[DEBUG] run_playwright_button: Playwright 실행 버튼 클릭됨.")
        asyncio.create_task(self.init_playwright())

    async def init_playwright(self):
        print("[DEBUG] init_playwright: Initializing Playwright...")
        self.page, self.browser, self.playwright = await run_playwright()
        self.check_button.setEnabled(True)
        print("[INFO] init_playwright: Playwright initialized and check button enabled.")

    def check_category_button(self):
        if self.page:
            print("[DEBUG] check_category_button: 요소 검사 버튼 클릭됨.")
            asyncio.create_task(self.handle_category_action())

    async def handle_category_action(self):
        print("[DEBUG] handle_category_action: Handling category action...")
        handler = CategoryHandler(self.page)
        await handler.handle_category_action()
        print("[INFO] handle_category_action: Category check completed.")

if __name__ == "__main__":
    print("[DEBUG] Main: Starting application...")
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    window = MainWindow()
    window.show()

    with loop:
        sys.exit(loop.run_forever())