# [DEF:PluginExampleShot:Module]
# @TIER: STANDARD
# @SEMANTICS: Plugin, Core, Extension
# @PURPOSE: Reference implementation of a plugin following GRACE standards.
# @LAYER: Domain (Business Logic)
# @RELATION: INHERITS -> PluginBase
# @INVARIANT: get_schema must return valid JSON Schema.

from typing import Dict, Any, Optional
from ..core.plugin_base import PluginBase
from ..core.task_manager.context import TaskContext
# GRACE: Обязательный импорт семантического логгера
from ..core.logger import logger, belief_scope

# [DEF:ExamplePlugin:Class]
# @PURPOSE: A sample plugin to demonstrate execution context and logging.
class ExamplePlugin(PluginBase):
    @property
    def id(self) -> str:
        return "example-plugin"

    #[DEF:get_schema:Function]
    # @PURPOSE: Defines input validation schema.
    # @DATA_CONTRACT: Input -> None, Output -> Dict (JSON Schema draft 7)
    def get_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "message": {
                    "type": "string",
                    "default": "Hello, GRACE!",
                }
            },
            "required": ["message"],
        }
    #[/DEF:get_schema:Function]

    # [DEF:execute:Function]
    # @PURPOSE: Core plugin logic with structured logging and scope isolation.
    # @DATA_CONTRACT: Input -> (params: Dict, context: Optional[TaskContext]), Output -> None
    # @PRE: params must be validated against get_schema() before calling.
    # @POST: Plugin payload is processed; progress is reported if context exists.
    # @SIDE_EFFECT: Emits logs to centralized system and TaskContext.
    async def execute(self, params: Dict, context: Optional[TaskContext] = None):
        message = params.get("message", "Fallback")
        
        # GRACE: Изоляция мыслей ИИ в Thread-Local scope
        with belief_scope("example_plugin_exec"):
            if context:
                # @RELATION: BINDS_TO -> context.logger
                log = context.logger.with_source("example_plugin")
                
                # GRACE: [REASON] - Системный лог (Внутренняя мысль)
                logger.reason("TaskContext provided. Binding task logger.", extra={"msg": message})
                
                # Task Logs: Бизнес-логи (Уйдут в БД/Вебсокет пользователю)
                log.info("Starting execution", extra={"msg": message})
                log.progress("Processing...", percent=50)
                log.info("Execution completed.")
                
                # GRACE: [REFLECT] - Сверка успешного выхода
                logger.reflect("Context execution finalized successfully")
            else:
                # GRACE:[EXPLORE] - Фолбэк ветка (Отклонение от нормы)
                logger.explore("No TaskContext provided. Running standalone.")
                
                # Standalone Fallback
                print(f"Standalone execution: {message}")
                
                # GRACE: [REFLECT] - Сверка выхода фолбэка
                logger.reflect("Standalone execution finalized")
    # [/DEF:execute:Function]

#[/DEF:ExamplePlugin:Class]
# [/DEF:PluginExampleShot:Module]