"""Project mixin: hot-swap code mounts between projects."""

from __future__ import annotations

import structlog

from proxym.virt._config import VMConfig
from proxym.virt._enums import VMState

logger = structlog.get_logger()


class _ProjectMixin:
    """Project switching (hot-swap code mounts)."""

    def switch_project(self, vm_id: str, new_project_path: str) -> bool:
        """Hot-swap the code mount to a different project directory.

        Uses virtiofs or 9p — requires VM to use shared filesystem.
        For simplicity, we update the config and remount.
        """
        vm = self.vms.get(vm_id)
        if not vm:
            return False

        old_path = vm.code_mount_host
        vm.code_mount_host = new_project_path
        self._save_config(vm)

        if vm.state == VMState.RUNNING:
            self._remount_project(vm, vm_id)

        logger.info("project_switched", vm=vm_id, old=old_path, new=new_project_path)
        return True

    def _remount_project(self, vm: VMConfig, vm_id: str) -> None:
        """SSH into VM and remount shared filesystem."""
        status = self.get_status(vm_id)
        if not status or not status.ip_address:
            return
        self._run(
            f"ssh -o StrictHostKeyChecking=no dev@{status.ip_address} "
            f"'sudo mount -t 9p -o trans=virtio code_share {vm.code_mount_guest}'",
            check=False,
        )
