import time
from typing import Any
from core.exceptions import ForbiddenError, ValidationError
from core.logging import get_logger
from modules.plugins.models import Plugin, TenantPlugin
from modules.plugins.schemas import ExecutePluginHookResponse

logger = get_logger(__name__)


class PluginExecutor:
    """Safe execution sandbox for running plugin hooks with capability restrictions."""

    REQUIRED_CAPABILITIES = {
        "on_message": "messages:read",
        "on_user_join": "users:read",
        "on_command": "messages:write",
        "fetch_external": "external:http",
    }

    @staticmethod
    def verify_permission(tenant_plugin: TenantPlugin, hook_name: str) -> None:
        required = PluginExecutor.REQUIRED_CAPABILITIES.get(hook_name)
        if required and required not in tenant_plugin.granted_permissions:
            raise ForbiddenError(
                f"Plugin execution forbidden: missing required capability '{required}' for hook '{hook_name}'."
            )

    @classmethod
    async def execute_hook(
        cls,
        tenant_plugin: TenantPlugin,
        plugin_meta: Plugin,
        hook_name: str,
        payload: dict[str, Any],
    ) -> ExecutePluginHookResponse:
        """
        Executes a plugin lifecycle hook in safe isolation.
        Catches runtime exceptions to prevent crashing the host application.
        """
        logs = []
        logs.append(f"[{time.strftime('%X')}] Initializing plugin '{plugin_meta.name}' v{tenant_plugin.installed_version}")

        # 1. Permission check
        cls.verify_permission(tenant_plugin, hook_name)
        logs.append(f"[{time.strftime('%X')}] Capability check passed for hook '{hook_name}'")

        output = {}
        try:
            # 2. Hook logic based on plugin ID
            pid = plugin_meta.id

            if pid == "welcome_captcha":
                user_id = payload.get("user_id", "unknown")
                logs.append(f"[{time.strftime('%X')}] Generating verification challenge for user {user_id}")
                output = {
                    "action": "send_captcha",
                    "challenge": "What is 4 + 7?",
                    "expected_answer": "11",
                    "timeout_seconds": tenant_plugin.config.get("timeout_seconds", 60),
                }

            elif pid == "crypto_price_tracker":
                symbol = payload.get("symbol", tenant_plugin.config.get("default_symbol", "BTC")).upper()
                logs.append(f"[{time.strftime('%X')}] Looking up price quote for {symbol}")
                # Mock high-fidelity market data
                price_map = {"BTC": 96450.0, "ETH": 2780.0, "SOL": 195.0, "TON": 5.40}
                price = price_map.get(symbol, 100.0)
                output = {
                    "symbol": symbol,
                    "price_usd": price,
                    "formatted": f"${price:,.2f}",
                    "24h_change": "+3.45%",
                }

            elif pid == "sentiment_analyzer":
                text = payload.get("text", "")
                logs.append(f"[{time.strftime('%X')}] Analyzing sentiment for text: '{text[:30]}'")
                # Deterministic sentiment classifier
                lower_text = text.lower()
                if any(w in lower_text for w in ["great", "love", "awesome", "good", "thanks"]):
                    sentiment = "positive"
                    score = 0.92
                elif any(w in lower_text for w in ["bad", "terrible", "worst", "broken", "hate"]):
                    sentiment = "negative"
                    score = -0.85
                else:
                    sentiment = "neutral"
                    score = 0.05
                output = {"sentiment": sentiment, "confidence_score": score}

            elif pid == "auto_support_router":
                query = payload.get("query", "")
                logs.append(f"[{time.strftime('%X')}] Categorizing support query")
                category = "billing" if "bill" in query.lower() or "pay" in query.lower() else "general"
                output = {
                    "ticket_created": True,
                    "routed_department": category,
                    "priority": "high" if "refund" in query.lower() else "normal",
                }

            else:
                logs.append(f"[{time.strftime('%X')}] Generic plugin executed successfully")
                output = {"status": "ok", "plugin_id": pid, "payload_received": payload}

            logs.append(f"[{time.strftime('%X')}] Hook '{hook_name}' completed execution successfully")
            return ExecutePluginHookResponse(
                success=True,
                hook_name=hook_name,
                output=output,
                logs=logs,
            )

        except Exception as exc:
            logger.error("plugin_execution_exception", plugin_id=plugin_meta.id, error=str(exc))
            logs.append(f"[{time.strftime('%X')}] ERROR: Execution error - {str(exc)}")
            return ExecutePluginHookResponse(
                success=False,
                hook_name=hook_name,
                output={"error": str(exc)},
                logs=logs,
            )
