"""Run tool — start or stop the Godot game from the editor."""

from __future__ import annotations

import os
from pathlib import Path

from godotiq.bridge.session import get_bridge


def _compute_timeout(explicit_timeout: float) -> float:
    """Compute scene launch timeout based on project asset count.

    If explicit_timeout > 0, return it directly.
    Otherwise, count .glb files under GODOTIQ_PROJECT_ROOT:
      >100 GLB → 20.0s
      >50  GLB → 15.0s
      else     → 10.0s
    If GODOTIQ_PROJECT_ROOT is not set → 15.0s default.
    """
    if explicit_timeout > 0:
        return explicit_timeout

    root = os.environ.get("GODOTIQ_PROJECT_ROOT")
    if not root:
        return 15.0

    try:
        glb_count = sum(1 for _ in Path(root).rglob("*.glb"))
    except Exception:
        return 15.0

    if glb_count > 100:
        return 20.0
    if glb_count > 50:
        return 15.0
    return 10.0


async def run(
    action: str = "play",
    scene: str = "main",
    timeout: float = 0,
) -> dict:
    """Start or stop the Godot game from the editor.

    Args:
        action: "play" to start, "stop" to halt the running game.
        scene: Which scene to run — "main", "current", or a res:// path.
            Only used with action="play".
        timeout: Timeout in seconds. 0 means auto-detect from GLB count.

    Returns:
        Dict with action, success, scene, waited_seconds from bridge.
    """
    bridge = await get_bridge()

    if action == "stop":
        await bridge.request("stop")
        return {"action": "stop"}

    computed_timeout = _compute_timeout(timeout)
    result = await bridge.request(
        "run",
        params={"scene": scene, "timeout": computed_timeout},
        timeout=computed_timeout + 5,
    )
    return result
