"""Run a tool, a dependent batch, or an interactive example shell."""
import argparse
import asyncio

from fastmcp import Client

from biome_mcp.batch.executor import BatchExecutor
from biome_mcp.batch.parser import parse_batch
from biome_mcp.cli.app import BiomeCLI
from biome_mcp.cli.provider import MCPToolProvider
from biome_mcp.mcp.compose import CompactMCP, strip_titles
from biome_mcp.models.result import CommandResult

server = CompactMCP("capture", schema_hooks=[strip_titles])


@server.tool
def frame_count(seconds: int, fps: int) -> int:
    """Calculate how many frames a capture will contain."""
    return seconds * fps


async def run_tool(seconds: int, fps: int) -> None:
    async with Client(server) as client:
        reply = await client.call_tool("frame_count", {"seconds": seconds, "fps": fps})
        print(f"Capture length: {reply.content[0].text} frames")


async def run_batch(seconds: int, fps: int, kib_per_frame: int) -> None:
    async def dispatch(name: str, values: dict[str, int]) -> CommandResult:
        if name == "frames":
            count = values["seconds"] * values["fps"]
            return CommandResult.ok(f"Capture length: {count} frames", data={"count": count})
        if name == "estimate":
            size = values["frames"] * values["kib_per_frame"]
            return CommandResult.ok(f"Estimated storage: {size:,} KiB")
        return CommandResult.error("UNKNOWN_COMMAND", name)

    commands = parse_batch(
        f"capture: frames seconds={seconds} fps={fps}\n"
        f"estimate frames=$capture.count kib_per_frame={kib_per_frame}"
    )
    for step in await BatchExecutor(dispatch).run(commands):
        print(step.result.text)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("task", choices=["tool", "batch", "shell"])
    parser.add_argument("--seconds", type=int)
    parser.add_argument("--fps", type=int)
    parser.add_argument("--kib-per-frame", type=int, default=128)
    args = parser.parse_args()
    if args.task == "shell":
        BiomeCLI(MCPToolProvider(server), name="capture").dispatch(["shell"])
    if args.seconds is None or args.fps is None:
        parser.error("--seconds and --fps are required for tool and batch")
    if args.task == "tool":
        asyncio.run(run_tool(args.seconds, args.fps))
    else:
        asyncio.run(run_batch(args.seconds, args.fps, args.kib_per_frame))
