import json
from datetime import datetime
from typing import Any, Dict

from dateutil.tz import UTC

from filum_utils.clients.common import BaseClient
from filum_utils.clients.notification.enums import (
    ToolLogActionEnum,
    ToolLogCodeEnum,
    ToolLogTypeEnum,
)
from filum_utils.clients.notification.types import Route
from filum_utils.config import config
from filum_utils.enums import ObjectType


class NotificationClient(BaseClient):
    def __init__(self):
        super().__init__(
            base_url=config.NOTIFICATION_BASE_URL,
            username=config.NOTIFICATION_USERNAME,
            password=config.NOTIFICATION_PASSWORD,
        )

    def create_notification(
        self,
        publisher_type: str,
        title: str,
        subtitle: str,
        route: Route,
        member_account_id: int = None,
        member_organization_id: str = None,
    ):
        notification = {
            "title": title,
            "subtitle": subtitle,
            "publisher_type": publisher_type,
            "route": route,
            "member_account_id": member_account_id,
            "member_organization_id": member_organization_id,
        }

        return self._request(
            method="POST", endpoint="/internal/notifications", data=notification
        )

    def log_tool_execution(
        self,
        title: str,
        subtitle: str,
        tool_id: str,
        input_data: Dict[str, Any],
        output_data: Dict[str, Any],
        execution_time: int,
        status: str,
        organization_id: str,
        account_id: int = None,
    ):
        log_data = {
            "code": ToolLogCodeEnum.EXECUTE,
            "type": ToolLogTypeEnum.INFO,
            "data": json.dumps(
                {
                    "toolId": tool_id,
                    "input": input_data,
                    "output": output_data,
                    "executionTime": execution_time,
                    "status": status,
                }
            ),
            "title": title,
            "subtitle": subtitle,
            "object_type": ObjectType.TOOL,
            "object_id": tool_id,
            "member_organization_id": organization_id,
            "action": ToolLogActionEnum.EXECUTE,
            "created": datetime.now().astimezone(tz=UTC).isoformat(),
        }

        if account_id:
            log_data["member_account_id"] = account_id

        return self._request(
            method="POST",
            endpoint="/internal/logs",
            data=log_data,
        )
