"""Guest file operations: copy files from guest VMs to host via VBoxManage."""

from __future__ import annotations

import os
from typing import Annotated

from fastmcp.exceptions import ToolError
from fastmcp.tools import tool
from pydantic import Field

from mcp_vm_blackbox._helpers import _resolve, _vbox
from mcp_vm_blackbox.models import VmCopyResult

_VAGRANT_USER = os.environ.get("VM_GUEST_USERNAME", "vagrant")
_VAGRANT_PASSWORD = os.environ.get("VM_GUEST_PASSWORD", "vagrant")


@tool
async def vm_copy_from_guest(
    vm_name: Annotated[str, Field(description="VirtualBox VM name.")],
    guest_path: Annotated[str, Field(description="Source path inside the guest VM.")],
    host_path: Annotated[str, Field(description="Destination path on the host.")],
    target: Annotated[
        str, Field(description='Named target ("local", "ci") or raw SSH string ("user@host").')
    ] = "local",
    username: Annotated[str, Field(description="Guest OS username for authentication.")] = _VAGRANT_USER,
    password: Annotated[str, Field(description="Guest OS password for authentication.")] = _VAGRANT_PASSWORD,
) -> VmCopyResult:
    """Copy a file from the guest VM to the host via VBoxManage guestcontrol.

    Wraps VBoxDispatch.copy_from_vm which executes:
        VBoxManage guestcontrol <vm> copyfrom --username <user> --password <pass> <guest_src> <local_dst>

    Args:
        vm_name: VirtualBox VM name.
        guest_path: Source path inside the guest VM.
        host_path: Destination path on the host.
        target: Named target or raw SSH string.
        username: Guest OS username for authentication.
        password: Guest OS password for authentication.

    Returns:
        VmCopyResult with success, guest_path, host_path, and optional error.

    Raises:
        ToolError: When VBoxManage fails (VM not found, authentication error,
            file not found, etc.).
    """
    cfg = _resolve(target)
    try:
        await _vbox(cfg, vm_name).copy_from_vm(
            guest_src=guest_path, local_dst=host_path, username=username, password=password
        )
    except RuntimeError as exc:
        # Map VBoxManage failures to ToolError with full stderr for diagnosis
        raise ToolError(f"Failed to copy '{guest_path}' from VM '{vm_name}' to '{host_path}': {exc}") from exc

    return VmCopyResult(success=True, guest_path=guest_path, host_path=host_path, error=None)
