from __future__ import annotations

import logging
from typing import Any

from .common import _utc_timestamp

logger = logging.getLogger("dscons.desktop_automation.zalo_chat")


class DesktopZaloChatMixin:
    """Zalo chat window navigation and active conversation verification."""

    async def zalo_open_chat(
        self,
        target_type: str,
        target_name: str | None = None,
    ) -> dict[str, Any]:
        """Open a Zalo chat either by contact name or My Document."""
        if target_type == "my_document":
            try:
                result = await self._run_mcp_server_tool(
                    "zalo_open_my_documents",
                    {"search_term": target_name or "My Documents"},
                )
                result.setdefault("data", {})
                result["data"].update(
                    {
                        "target_type": target_type,
                        "target_name": target_name,
                        "resolved_target_name": "My Documents",
                        "backend": "local_mcp_direct",
                        "implemented": True,
                        "execution_mode": "live_mcp",
                    }
                )
                return result
            except Exception as exc:
                resolved_name = "My Documents"
                return {
                    "ok": False,
                    "action": "zalo_open_chat",
                    "timestamp": _utc_timestamp(),
                    "data": {
                        "target_type": target_type,
                        "target_name": target_name,
                        "resolved_target_name": resolved_name,
                        "backend": "mcp_error",
                    },
                    "artifacts": {},
                    "error": {
                        "code": "zalo_open_chat_failed",
                        "message": str(exc),
                        "details": {"supported_target_type": "my_document"},
                    },
                }

        return {
            "ok": False,
            "action": "zalo_open_chat",
            "timestamp": _utc_timestamp(),
            "data": {
                "target_type": target_type,
                "target_name": target_name,
                "backend": "unsupported",
            },
            "artifacts": {},
            "error": {
                "code": "unsupported_target",
                "message": "Contact chat opening is not available in the current DSCons desktop backend.",
                "details": {"supported_target_type": "my_document"},
            },
        }

    async def zalo_verify_active_chat(
        self,
        expected_name: str,
        allow_partial_match: bool = True,
    ) -> dict[str, Any]:
        """Verify the active Zalo chat title before sending any action."""
        expected_normalized = expected_name.strip().lower()
        is_supported = expected_normalized in {"my document", "my documents"}

        if is_supported:
            return {
                "ok": True,
                "action": "zalo_verify_active_chat",
                "timestamp": _utc_timestamp(),
                "data": {
                    "expected_name": expected_name,
                    "matched_name": "My Documents",
                    "allow_partial_match": allow_partial_match,
                    "verification_mode": "heuristic_without_ocr",
                    "backend": "local_contract",
                    "implemented": True,
                    "notes": [
                        "Verification is currently inferred from the dedicated My Documents workflow.",
                        "OCR/title scraping is not yet installed.",
                    ],
                },
                "artifacts": {},
                "error": None,
            }

        return {
            "ok": False,
            "action": "zalo_verify_active_chat",
            "timestamp": _utc_timestamp(),
            "data": {
                "expected_name": expected_name,
                "allow_partial_match": allow_partial_match,
                "backend": "unsupported",
            },
            "artifacts": {},
            "error": {
                "code": "unsupported_target",
                "message": "Chat verification is only available for the My Documents workflow in the current backend.",
                "details": {"supported_expected_name": "My Document"},
            },
        }
