import json
from typing import override

from flask_restx import fields

from fields.workflow_fields import workflow_partial_fields
from libs.helper import AppIconUrlField, TimestampField


class JsonStringField(fields.Raw):
    @override
    def format(self, value):
        if isinstance(value, str):
            try:
                return json.loads(value)
            except (json.JSONDecodeError, TypeError):
                return value
        return value


class OpaqueRawField(fields.Raw):
    @override
    def schema(self) -> dict[str, object]:
        return {"type": "object"}


class StringListRawField(fields.Raw):
    @override
    def schema(self) -> dict[str, object]:
        return {"type": "array", "items": {"type": "string"}}


class ObjectListRawField(fields.Raw):
    @override
    def schema(self) -> dict[str, object]:
        return {"type": "array", "items": {"type": "object"}}


app_detail_kernel_fields = {
    "id": fields.String,
    "name": fields.String,
    "description": fields.String,
    "mode": fields.String(attribute="mode_compatible_with_agent"),
    "icon_type": fields.String,
    "icon": fields.String,
    "icon_background": fields.String,
    "icon_url": AppIconUrlField,
}

related_app_list = {
    "data": fields.List(fields.Nested(app_detail_kernel_fields)),
    "total": fields.Integer,
}

model_config_fields = {
    "opening_statement": fields.String,
    "suggested_questions": StringListRawField(attribute="suggested_questions_list"),
    "suggested_questions_after_answer": OpaqueRawField(attribute="suggested_questions_after_answer_dict"),
    "speech_to_text": OpaqueRawField(attribute="speech_to_text_dict"),
    "text_to_speech": OpaqueRawField(attribute="text_to_speech_dict"),
    "retriever_resource": OpaqueRawField(attribute="retriever_resource_dict"),
    "annotation_reply": OpaqueRawField(attribute="annotation_reply_dict"),
    "more_like_this": OpaqueRawField(attribute="more_like_this_dict"),
    "sensitive_word_avoidance": OpaqueRawField(attribute="sensitive_word_avoidance_dict"),
    "external_data_tools": ObjectListRawField(attribute="external_data_tools_list"),
    "model": OpaqueRawField(attribute="model_dict"),
    "user_input_form": ObjectListRawField(attribute="user_input_form_list"),
    "dataset_query_variable": fields.String,
    "pre_prompt": fields.String,
    "agent_mode": OpaqueRawField(attribute="agent_mode_dict"),
    "prompt_type": fields.String,
    "chat_prompt_config": OpaqueRawField(attribute="chat_prompt_config_dict"),
    "completion_prompt_config": OpaqueRawField(attribute="completion_prompt_config_dict"),
    "dataset_configs": OpaqueRawField(attribute="dataset_configs_dict"),
    "file_upload": OpaqueRawField(attribute="file_upload_dict"),
    "created_by": fields.String,
    "created_at": TimestampField,
    "updated_by": fields.String,
    "updated_at": TimestampField,
}

tag_fields = {"id": fields.String, "name": fields.String, "type": fields.String}

app_detail_fields = {
    "id": fields.String,
    "name": fields.String,
    "description": fields.String,
    "mode": fields.String(attribute="mode_compatible_with_agent"),
    "icon": fields.String,
    "icon_background": fields.String,
    "enable_site": fields.Boolean,
    "enable_api": fields.Boolean,
    "model_config": fields.Nested(model_config_fields, attribute="app_model_config", allow_null=True),
    "workflow": fields.Nested(workflow_partial_fields, allow_null=True),
    "tracing": OpaqueRawField,
    "use_icon_as_answer_icon": fields.Boolean,
    "created_by": fields.String,
    "created_at": TimestampField,
    "updated_by": fields.String,
    "updated_at": TimestampField,
    "access_mode": fields.String,
    "tags": fields.List(fields.Nested(tag_fields)),
}

prompt_config_fields = {
    "prompt_template": fields.String,
}

model_config_partial_fields = {
    "model": OpaqueRawField(attribute="model_dict"),
    "pre_prompt": fields.String,
    "created_by": fields.String,
    "created_at": TimestampField,
    "updated_by": fields.String,
    "updated_at": TimestampField,
}

app_partial_fields = {
    "id": fields.String,
    "name": fields.String,
    "max_active_requests": OpaqueRawField(),
    "description": fields.String(attribute="desc_or_prompt"),
    "mode": fields.String(attribute="mode_compatible_with_agent"),
    "icon_type": fields.String,
    "icon": fields.String,
    "icon_background": fields.String,
    "icon_url": AppIconUrlField,
    "model_config": fields.Nested(model_config_partial_fields, attribute="app_model_config", allow_null=True),
    "workflow": fields.Nested(workflow_partial_fields, allow_null=True),
    "use_icon_as_answer_icon": fields.Boolean,
    "created_by": fields.String,
    "created_at": TimestampField,
    "updated_by": fields.String,
    "updated_at": TimestampField,
    "tags": fields.List(fields.Nested(tag_fields)),
    "access_mode": fields.String,
    "create_user_name": fields.String,
    "author_name": fields.String,
    "has_draft_trigger": fields.Boolean,
}


app_pagination_fields = {
    "page": fields.Integer,
    "limit": fields.Integer(attribute="per_page"),
    "total": fields.Integer,
    "has_more": fields.Boolean(attribute="has_next"),
    "data": fields.List(fields.Nested(app_partial_fields), attribute="items"),
}

template_fields = {
    "name": fields.String,
    "icon": fields.String,
    "icon_background": fields.String,
    "description": fields.String,
    "mode": fields.String,
    "model_config": fields.Nested(model_config_fields),
}

template_list_fields = {
    "data": fields.List(fields.Nested(template_fields)),
}

site_fields = {
    "access_token": fields.String(attribute="code"),
    "code": fields.String,
    "title": fields.String,
    "icon_type": fields.String,
    "icon": fields.String,
    "icon_background": fields.String,
    "icon_url": AppIconUrlField,
    "description": fields.String,
    "default_language": fields.String,
    "chat_color_theme": fields.String,
    "chat_color_theme_inverted": fields.Boolean,
    "customize_domain": fields.String,
    "copyright": fields.String,
    "privacy_policy": fields.String,
    "custom_disclaimer": fields.String,
    "customize_token_strategy": fields.String,
    "prompt_public": fields.Boolean,
    "app_base_url": fields.String,
    "show_workflow_steps": fields.Boolean,
    "use_icon_as_answer_icon": fields.Boolean,
    "created_by": fields.String,
    "created_at": TimestampField,
    "updated_by": fields.String,
    "updated_at": TimestampField,
}

deleted_tool_fields = {
    "type": fields.String,
    "tool_name": fields.String,
    "provider_id": fields.String,
}

app_detail_fields_with_site = {
    "id": fields.String,
    "name": fields.String,
    "description": fields.String,
    "mode": fields.String(attribute="mode_compatible_with_agent"),
    "icon_type": fields.String,
    "icon": fields.String,
    "icon_background": fields.String,
    "icon_url": AppIconUrlField,
    "enable_site": fields.Boolean,
    "enable_api": fields.Boolean,
    "model_config": fields.Nested(model_config_fields, attribute="app_model_config", allow_null=True),
    "workflow": fields.Nested(workflow_partial_fields, allow_null=True),
    "api_base_url": fields.String,
    "use_icon_as_answer_icon": fields.Boolean,
    "max_active_requests": fields.Integer,
    "created_by": fields.String,
    "created_at": TimestampField,
    "updated_by": fields.String,
    "updated_at": TimestampField,
    "deleted_tools": fields.List(fields.Nested(deleted_tool_fields)),
    "access_mode": fields.String,
    "tags": fields.List(fields.Nested(tag_fields)),
    "site": fields.Nested(site_fields),
}


app_site_fields = {
    "app_id": fields.String,
    "access_token": fields.String(attribute="code"),
    "code": fields.String,
    "title": fields.String,
    "icon": fields.String,
    "icon_background": fields.String,
    "description": fields.String,
    "default_language": fields.String,
    "customize_domain": fields.String,
    "copyright": fields.String,
    "privacy_policy": fields.String,
    "custom_disclaimer": fields.String,
    "customize_token_strategy": fields.String,
    "prompt_public": fields.Boolean,
    "show_workflow_steps": fields.Boolean,
    "use_icon_as_answer_icon": fields.Boolean,
}

leaked_dependency_fields = {"type": fields.String, "value": OpaqueRawField, "current_identifier": fields.String}

app_import_fields = {
    "id": fields.String,
    "status": fields.String,
    "app_id": fields.String,
    "app_mode": fields.String,
    "current_dsl_version": fields.String,
    "imported_dsl_version": fields.String,
    "error": fields.String,
}

app_import_check_dependencies_fields = {
    "leaked_dependencies": fields.List(fields.Nested(leaked_dependency_fields)),
}

app_server_fields = {
    "id": fields.String,
    "name": fields.String,
    "server_code": fields.String,
    "description": fields.String,
    "status": fields.String,
    "parameters": JsonStringField,
    "created_at": TimestampField,
    "updated_at": TimestampField,
}
