"""Common utilities for MCP server.

This module provides shared utility functions used across the MCP server,
including file polling and other async helpers.
"""

from __future__ import annotations

import asyncio
import logging
import time
from pathlib import Path

__all__ = ["wait_for_gds_file"]

logger = logging.getLogger(__name__)


async def wait_for_gds_file(
    gds_path: Path,
    timeout: float = 30.0,
    poll_interval: float = 0.5,
    min_age: float = 0.1,
) -> bool:
    """Poll for GDS file to be created with timeout.

    This function waits for a GDS file to exist and be stable (not actively
    being written to) before returning. Useful for waiting on build operations.

    Args:
        gds_path: Path to the expected GDS file
        timeout: Maximum time to wait in seconds (default: 30.0)
        poll_interval: Time between polls in seconds (default: 0.5)
        min_age: Minimum file age in seconds to ensure write is complete (default: 0.1)

    Returns:
        True if file exists and is ready, False if timeout reached
    """
    start_time = time.monotonic()
    logger.debug("Waiting for GDS file: %s (timeout: %.1fs)", gds_path, timeout)

    while time.monotonic() - start_time < timeout:
        if gds_path.exists():
            file_age = time.time() - gds_path.stat().st_mtime
            if file_age >= min_age:
                logger.debug("GDS file ready: %s (age: %.2fs)", gds_path, file_age)
                return True
            logger.debug(
                "GDS file exists but too new (age: %.2fs), waiting...", file_age
            )

        await asyncio.sleep(poll_interval)

    logger.warning("Timeout waiting for GDS file: %s", gds_path)
    return False
