"""Browser session health checker.

Checks if the current browser session is still authenticated on a domain
by navigating to a known URL and checking for success/failure indicators.
"""
from __future__ import annotations

import asyncio
from dataclasses import dataclass
from typing import Any

from loguru import logger


@dataclass(frozen=True)
class SessionHealthResult:
    """Result of a session health check."""

    domain: str
    is_authenticated: bool
    indicators_found: list[str]
    login_wall_detected: bool
    check_url: str
    page_title: str = ""
    error: str | None = None


async def check_session_health(
    page: Any,
    *,
    check_url: str,
    success_indicators: list[str],
    login_wall_indicators: list[str],
    timeout_ms: int = 10000,
) -> SessionHealthResult:
    """Check if current browser session is authenticated.

    Navigates to check_url and looks for success/login-wall indicators
    in the page text content.
    """
    from urllib.parse import urlparse

    domain = urlparse(check_url).netloc or check_url

    try:
        await page.goto(check_url, wait_until="domcontentloaded", timeout=timeout_ms)
        await asyncio.sleep(1.0)  # Let dynamic content load

        page_text = await page.evaluate("() => document.body?.innerText || ''")
        page_title = await page.evaluate("() => document.title || ''")
        full_text = f"{page_title} {page_text}".lower()

        found_success = [
            ind for ind in success_indicators if ind.lower() in full_text
        ]
        found_login_wall = [
            ind for ind in login_wall_indicators if ind.lower() in full_text
        ]

        is_authenticated = bool(found_success) and not bool(found_login_wall)

        return SessionHealthResult(
            domain=domain,
            is_authenticated=is_authenticated,
            indicators_found=found_success,
            login_wall_detected=bool(found_login_wall),
            check_url=check_url,
            page_title=page_title,
        )
    except Exception as exc:
        logger.warning("Session health check failed for {}: {}", domain, exc)
        return SessionHealthResult(
            domain=domain,
            is_authenticated=False,
            indicators_found=[],
            login_wall_detected=False,
            check_url=check_url,
            error=str(exc),
        )


async def check_domain_session(
    page: Any,
    domain_skill: Any,
) -> SessionHealthResult:
    """Check session health using a DomainSkill's auth_check config."""
    if domain_skill.auth_check is None:
        return SessionHealthResult(
            domain=domain_skill.domain,
            is_authenticated=True,  # No auth check defined = assume OK
            indicators_found=[],
            login_wall_detected=False,
            check_url="",
        )

    return await check_session_health(
        page,
        check_url=domain_skill.auth_check.url,
        success_indicators=domain_skill.auth_check.success_indicators,
        login_wall_indicators=domain_skill.auth_check.login_wall_indicators,
    )
