import json
from copy import deepcopy
from enum import Flag, auto
from typing import Any

from pydantic import BaseModel


class ActivityType(Flag):
    BROWSER = auto()  # 1
    APP = auto()  # 2


def truncate_base64_fields(data: Any, truncate_length: int = 10) -> Any:
    if isinstance(data, dict):
        new_data = {}
        for key, value in data.items():
            # 如果是base64图片字段，截断
            if key in [
                "screenshots",
                "screenshotsBase64",
                "screenshots_base64",
            ] and isinstance(value, list):
                truncated_list = [
                    (item[:truncate_length] + "...")
                    if isinstance(item, str) and len(item) > truncate_length
                    else item
                    for item in value
                ]
                new_data[key] = truncated_list
            else:
                new_data[key] = truncate_base64_fields(value, truncate_length)
        return new_data
    elif isinstance(data, list):
        return [truncate_base64_fields(item, truncate_length) for item in data]
    else:
        return data


class ResultModel(BaseModel):
    code: int
    data: Any = None
    message: str = ""

    @staticmethod
    def success(data: Any = None, message: str = "") -> "ResultModel":
        return ResultModel(code=200, data=data, message=message)

    @staticmethod
    def error(
        message: str,
        code: int = 500,
        data: Any = None,
    ) -> "ResultModel":
        return ResultModel(code=code, message=message, data=data)

    def log_str(self) -> str:
        try:
            raw_dict = self.dict()
            safe_dict = deepcopy(raw_dict)
            log = truncate_base64_fields(safe_dict)

            return json.dumps(
                log,
                default=lambda o: o.__dict__,
                ensure_ascii=False,
            )
        except Exception:
            return json.dumps(
                self,
                default=lambda o: o.__dict__,
                ensure_ascii=False,
            )
