from playwright.async_api import Page
import traceback

from app.automation.helpers import human_delay, find_and_click_next
from app.automation.selectors import (
    STATS_NO_OPTION, 
    STATS_YES_OPTION,
    STATS_TEAM_OPTION,
    STATS_PLAYER_OPTION
)
from app.automation.tasks.popup import close_hudl_popups


async def get_stats_options(page: Page) -> dict:
    """
    GET /exchange/stats
    Reads the options from the stats page.
    """
    await close_hudl_popups(page)
    await human_delay(1, 2)
    
    main_options = []
    sub_options = []
    try:
        radios = page.locator('xpath=//ul[@class="ko-radios"]/li')
        await radios.first.wait_for(state="attached", timeout=10000)
        count = await radios.count()
        for i in range(count):
            li = radios.nth(i)
            id_attr = await li.get_attribute("id")
            label = li.locator(".ko-choice-label").first
            text = (await label.inner_text()).strip() if await label.count() > 0 else (await li.inner_text()).strip()
            main_options.append({
                "id": id_attr,
                "text": text
            })
            
        checkboxes = page.locator('xpath=//ul[@class="ko-checkboxes"]/li')
        count = await checkboxes.count()
        for i in range(count):
            li = checkboxes.nth(i)
            id_attr = await li.get_attribute("id")
            label = li.locator(".ko-choice-label").first
            
            if await label.count() > 0:
                raw_text = await label.inner_text()
            else:
                raw_text = await li.inner_text()
                
            lines = [line.strip() for line in raw_text.split('\n') if line.strip()]
            title = lines[0] if len(lines) > 0 else ""
            description = lines[1] if len(lines) > 1 else ""
            
            sub_options.append({
                "id": id_attr,
                "title": title,
                "description": description
            })
            
    except Exception:
        pass
        
    return {
        "status": "ok",
        "action": "get_stats_options",
        "main_options": main_options,
        "sub_options": sub_options,
        "url": page.url,
        "message": f"Found {len(main_options)} main options and {len(sub_options)} sub options." if main_options else "No stats options found (may be skipped)."
    }


async def select_stats(page: Page, include_stats: bool, include_team_stats: bool = True, include_player_stats: bool = True) -> dict:
    """
    POST /exchange/stats
    Selects whether to include stats (and sub-options), then clicks Next.
    """
    await close_hudl_popups(page)
    await human_delay(1, 1.5)

    found_next_button = None
    try:
        if include_stats:
            option_locator = page.locator(STATS_YES_OPTION).first
        else:
            option_locator = page.locator(STATS_NO_OPTION).first

        if await option_locator.count() > 0 and await option_locator.is_visible():
            await option_locator.click()
            await human_delay(0.5, 1)
            
            if include_stats:
                # Handle sub options
                team_opt = page.locator(STATS_TEAM_OPTION).first
                if await team_opt.count() > 0 and await team_opt.is_visible():
                    class_attr = await team_opt.get_attribute("class") or ""
                    is_checked = "ko-checked" in class_attr
                    if include_team_stats != is_checked:
                        await team_opt.click()
                        await human_delay(0.3, 0.6)
                
                player_opt = page.locator(STATS_PLAYER_OPTION).first
                if await player_opt.count() > 0 and await player_opt.is_visible():
                    class_attr = await player_opt.get_attribute("class") or ""
                    is_checked = "ko-checked" in class_attr
                    if include_player_stats != is_checked:
                        await player_opt.click()
                        await human_delay(0.3, 0.6)

        found_next_button = await find_and_click_next(page)
        await human_delay(1.5, 2.5)

    except Exception as e:
        print(f"Error in select_stats: {e}")
        traceback.print_exc()
        raise

    await close_hudl_popups(page)

    return {
        "status": "ok",
        "action": "stats",
        "include_stats": include_stats,
        "include_team_stats": include_team_stats,
        "include_player_stats": include_player_stats,
        "url": page.url,
        "next_button_used": found_next_button,
        "message": f"Stats selection {'Included' if include_stats else 'Skipped'}, clicked Next dynamically.",
    }
