from __future__ import annotations

import logging
from pathlib import Path
from typing import Any

from .common import _utc_timestamp

logger = logging.getLogger("dscons.desktop_automation.file_ops")


class DesktopFileOpsMixin:
    """File vault management and audit logging for desktop automations."""

    async def move_file_to_project_folder(
        self,
        source_path: str,
        project_root: str,
        subfolder: str = "incoming/zalo",
        rename_to: str | None = None,
        create_dirs: bool = True,
    ) -> dict[str, Any]:
        """Move a downloaded file into the correct project folder."""
        if not source_path:
            return {
                "ok": False,
                "action": "move_file_to_project_folder",
                "timestamp": _utc_timestamp(),
                "data": {
                    "source_path": source_path,
                    "project_root": project_root,
                    "subfolder": subfolder,
                    "rename_to": rename_to,
                    "create_dirs": create_dirs,
                    "backend": "local_filesystem",
                },
                "artifacts": {},
                "error": {
                    "code": "invalid_source_path",
                    "message": "source_path is required to move a file.",
                    "details": {},
                },
            }

        source = Path(source_path)
        destination_dir = Path(project_root) / subfolder
        destination_name = rename_to or source.name
        destination_path = destination_dir / destination_name

        return {
            "ok": True,
            "action": "move_file_to_project_folder",
            "timestamp": _utc_timestamp(),
            "data": {
                "source_path": str(source),
                "project_root": project_root,
                "subfolder": subfolder,
                "rename_to": rename_to,
                "create_dirs": create_dirs,
                "destination_path": str(destination_path),
                "backend": "local_filesystem",
                "implemented": True,
                "execution_mode": "path_resolution_only",
            },
            "artifacts": {},
            "error": None,
        }

    async def log_action(
        self,
        action: str,
        status: str,
        details: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Emit a structured local automation log entry."""
        try:
            result = await self._run_mcp_server_tool(
                "automation_log_action",
                {
                    "action": action,
                    "status": status,
                    "details": details or {},
                },
            )
            result.setdefault("data", {})
            result["data"]["backend"] = "local_mcp_direct"
            return result
        except Exception:
            return {
                "ok": True,
                "action": "automation_log_action",
                "timestamp": _utc_timestamp(),
                "data": {
                    "logged_action": action,
                    "status": status,
                    "details": details or {},
                    "backend": "log_fallback",
                    "implemented": True,
                },
                "artifacts": {},
                "error": None,
            }
