import asyncio
from pathlib import Path
from typing import Any

from pydantic_ai_skills import SkillScript


def build_script_command(script_path: Path, args: dict[str, Any] | None) -> list[str]:
    cmd = ["uv", "run", script_path.as_posix()]
    if not args:
        return cmd

    for key, value in args.items():
        if isinstance(value, bool):
            if value:
                cmd.append(f"--{key}")
        elif isinstance(value, list):
            for item in value:
                cmd.extend([f"--{key}", str(item)])
        elif value is not None:
            cmd.extend([f"--{key}", str(value)])

    return cmd


async def execute_script_with_timeout(cmd: list[str], cwd: str, timeout: int = 60) -> str:
    try:
        proc = await asyncio.create_subprocess_exec(
            *cmd,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            cwd=cwd,
        )
        try:
            stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
        except TimeoutError:
            proc.kill()
            await proc.communicate()
            return f"Erro: tempo limite de {timeout} segundos excedido na execução do script"

        parts = [stdout.decode("utf-8", errors="replace")]
        if stderr:
            parts.append(f"Stderr:\n{stderr.decode('utf-8', errors='replace')}")
        if proc.returncode != 0:
            parts.append(f"Script exited with code {proc.returncode}")

        return "\n\n".join(parts).strip() or "(sem saída)"

    except OSError as e:
        return f"Erro ao executar script: {e}"


async def uv_script_executor(script: SkillScript, args: dict[str, Any] | None = None) -> str:
    if script.uri is None:
        return f"Erro: script '{script.name}' não possui URI para execução."
    script_path = Path(script.uri).resolve()
    cmd = build_script_command(script_path, args)
    return await execute_script_with_timeout(cmd, script_path.parent.as_posix())
