import logging
from pathlib import Path

from gsearch_mcp_cli.constants import (
    GOOGLE_ABOUT,
    GOOGLE_HOMEPAGE,
    GOOGLE_PREFERENCES,
    REQUIRED_WARMUP_COOKIES,
)
from gsearch_mcp_cli.exceptions import ProfileWarmupError

logger = logging.getLogger(__name__)


async def warmup_profile(browser_cdp) -> None:
    """Visit Google pages to establish BotGuard trust cookies.

    Creates a tab, navigates to Google homepage, about page, and preferences
    to accumulate the NID and AEC cookies that Google requires for search access.
    """
    async with browser_cdp.create_tab() as tab:
        logger.info("Warming up profile: visiting Google homepage")
        await tab.navigate(GOOGLE_HOMEPAGE)

        logger.info("Warming up profile: visiting About Google")
        await tab.navigate(GOOGLE_ABOUT)

        logger.info("Warming up profile: visiting Google Preferences")
        await tab.navigate(GOOGLE_PREFERENCES)

        cookies = await tab.get_cookies()
        cookie_names = {c["name"] for c in cookies}
        missing = REQUIRED_WARMUP_COOKIES - cookie_names

        if missing:
            raise ProfileWarmupError(
                f"Missing cookies after warmup: {missing}. "
                "Google may have changed its cookie behavior. "
                "Try: gsearch setup --reset"
            )

    logger.info("Profile warmup complete")


def needs_warmup(profile_dir: Path) -> bool:
    """Check if profile needs warming up.

    Returns True if the profile directory doesn't exist, is empty,
    or hasn't been marked as warmed up.
    """
    if not profile_dir.exists():
        return True
    marker = profile_dir / ".warmed_up"
    return not marker.exists()


def mark_warmed_up(profile_dir: Path) -> None:
    """Mark a profile as having been warmed up."""
    profile_dir.mkdir(parents=True, exist_ok=True)
    marker = profile_dir / ".warmed_up"
    marker.touch()
