"""Keepalive loop factory for browser daemons."""
from __future__ import annotations

import asyncio
from collections.abc import Callable
from datetime import datetime


def make_keepalive_loop(
    get_page_fn: Callable,
    page_lock: asyncio.Lock,
    keepalive_url: str,
    interval: int = 300,
    extra_action: Callable | None = None,
) -> Callable:
    """Return an async keepalive loop coroutine for use as asyncio task.

    get_page_fn: async callable that returns a live Playwright page
    extra_action: optional async callable(page) for real interaction (e.g. run a search)
    """
    async def loop(app=None):
        await asyncio.sleep(10)
        while True:
            try:
                async with page_lock:
                    page = await get_page_fn()
                    await page.goto(keepalive_url, timeout=15000)
                    await page.wait_for_load_state("networkidle", timeout=10000)
                    if extra_action:
                        await extra_action(page)
                    print(f"[{datetime.now().strftime('%H:%M')}] keep-alive ok", flush=True)
            except Exception as e:
                print(f"[{datetime.now().strftime('%H:%M')}] keep-alive error: {e}", flush=True)
            await asyncio.sleep(interval)
    return loop
