"""
Remote Tool document for IQ host.

Represents an Automation Tool definition on the remote host.
"""

from __future__ import annotations

import hashlib
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, ClassVar

from iq_sdk.client.remote import RemoteDocument

if TYPE_CHECKING:
    from iq_sdk.client.remote import IQApiClient


@dataclass
class RemoteTool(RemoteDocument):
    """
    Remote tool document.

    Represents a tool definition on the IQ host.
    Doctype: "Automation Tool"

    Note: The 'namespace' field is used to store the project name on the remote.
    Use the 'project_name' property for cleaner access.

    Remote fields: namespace, tool_name, tool (link), version, properties_json
    Local-only: digest (computed from properties)
    """

    doctype: ClassVar[str] = "Automation Tool"

    # Fields to query from remote
    remote_fields: ClassVar[list[str]] = [
        "namespace",
        "tool_name",
        "version",
        "digest",  # Stored on remote for comparison
    ]

    # Remote fields
    namespace: str = ""
    tool_name: str = ""
    version: str = ""  # e.g. "1.0", "1.1"
    properties_json: str = ""  # Sent on create/update, not queried
    digest: str = ""  # Stored on remote for comparison
    active: bool = True

    @classmethod
    def get_fields(cls) -> list[str]:
        """Get fields that exist on remote."""
        return ["name", "creation", "modified"] + cls.remote_fields

    @property
    def project_name(self) -> str:
        """Get project name (stored as 'namespace' on remote)."""
        return self.namespace

    @project_name.setter
    def project_name(self, value: str) -> None:
        """Set project name (stored as 'namespace' on remote)."""
        self.namespace = value

    def compute_local_digest(self) -> str:
        """Compute digest from current properties_json."""
        return self.compute_digest(
            self.namespace,
            self.tool_name,
            self.version,
            self.properties_json,
        )

    @classmethod
    def compute_digest(
        cls,
        project_name: str,
        tool_name: str,
        version: str,
        properties_json: str,
    ) -> str:
        """
        Compute digest for tool version.

        Digest is SHA256 of: project_name.tool_name.version.properties_json
        """
        content = f"{project_name}.{tool_name}.{version}.{properties_json}"
        return hashlib.sha256(content.encode()).hexdigest()[:16]

    def matches_digest(self, local_digest: str) -> bool:
        """Check if remote digest matches local."""
        return self.digest == local_digest

    @classmethod
    async def find_all_by_project(
        cls,
        client: IQApiClient,
        project_name: str,
    ) -> list[RemoteTool]:
        """Find all tools for a project (by namespace)."""
        return await cls.find_all(
            client,
            filters={"namespace": ("=", project_name)},
            order_by="tool_name asc, version desc",
        )

    @classmethod
    async def find_all_by_tool_name(
        cls,
        client: IQApiClient,
        project_name: str,
        tool_name: str,
        version: str | None = None,
    ) -> list[RemoteTool]:
        """Find all versions of a tool by name."""
        filters: dict[str, tuple[str, Any]] = {
            "namespace": ("=", project_name),
            "tool_name": ("=", tool_name),
        }
        if version:
            filters["version"] = ("=", version)

        return await cls.find_all(
            client,
            filters=filters,
            order_by="version desc",
        )
