import logging
import random
from time import sleep

from GramAddict.core.behaviors import BehaviorContext, BehaviorPlugin, BehaviorResult

logger = logging.getLogger(__name__)


class DarwinDwellPlugin(BehaviorPlugin):
    """
    Simulates human dwelling using the Darwin engine.

    Priority: 60 (Runs after evaluation, before interactions).
    """

    def __init__(self):
        super().__init__()
        self._enabled = True

    @property
    def name(self) -> str:
        return "darwin_dwell"

    @property
    def priority(self) -> int:
        return 60

    def can_activate(self, ctx: BehaviorContext) -> bool:
        if not getattr(self, "_enabled", True):
            return False

        config = self.get_config(ctx)
        percentage = float(config.get("percentage", 100))
        return random.random() < (percentage / 100.0)

    def execute(self, ctx: BehaviorContext) -> BehaviorResult:
        darwin = ctx.cognitive_stack.get("darwin")
        if darwin:
            logger.info("🐢 [DarwinDwell] Executing organic dwell behaviors...")
            darwin.execute_micro_wobble(ctx.device)
            res_score = ctx.shared_state.get("res_score", 1.0)
            darwin.execute_proof_of_resonance(
                ctx.device,
                res_score,
                nav_graph=ctx.cognitive_stack.get("nav_graph"),
                configs=ctx.configs,
                resonance_oracle=ctx.cognitive_stack.get("oracle"),
                username=ctx.username,
                context_xml=ctx.context_xml or ctx.device.dump_hierarchy(),
            )
        else:
            logger.info("🐢 [DarwinDwell] Darwin engine missing. Falling back to static sleep.")
            sleep(2.5 * ctx.sleep_mod)

        return BehaviorResult(executed=True)
