"""Seeds mixin — seed type selection and context gathering for thinking cycles."""

import logging
import random
from datetime import UTC, datetime

from timmy.thinking.seeds import (
    _CREATIVE_SEEDS,
    _EXISTENTIAL_SEEDS,
    _OBSERVATION_SEEDS,
    _SOVEREIGNTY_SEEDS,
    SEED_TYPES,
)

logger = logging.getLogger(__name__)


class _SeedsMixin:
    """Mixin providing seed-type selection and context-gathering for each thinking cycle.

    Expects the host class to provide:
    - self.get_recent_thoughts(limit) -> list[Thought]
    """

    # Reflective prompts layered on top of swarm data
    _SWARM_REFLECTIONS = [
        "What does this activity pattern tell me about the health of the system?",
        "Which tasks are flowing smoothly, and where is friction building up?",
        "If I were coaching these agents, what would I suggest they focus on?",
        "Is the swarm balanced, or is one agent carrying too much weight?",
        "What surprised me about recent task outcomes?",
    ]

    def _pick_seed_type(self) -> str:
        """Pick a seed type, avoiding types used in the last 3 thoughts.

        Ensures the thought stream doesn't fixate on one category.
        Falls back to the full pool if all types were recently used.
        """
        recent = self.get_recent_thoughts(limit=3)
        recent_types = {t.seed_type for t in recent}
        available = [t for t in SEED_TYPES if t not in recent_types]
        if not available:
            available = list(SEED_TYPES)
        return random.choice(available)

    def _gather_seed(self) -> tuple[str, str]:
        """Pick a seed type and gather relevant context.

        Returns (seed_type, seed_context_string).
        """
        seed_type = self._pick_seed_type()

        if seed_type == "swarm":
            return seed_type, self._seed_from_swarm()
        if seed_type == "scripture":
            return seed_type, self._seed_from_scripture()
        if seed_type == "memory":
            return seed_type, self._seed_from_memory()
        if seed_type == "creative":
            prompt = random.choice(_CREATIVE_SEEDS)
            return seed_type, f"Creative prompt: {prompt}"
        if seed_type == "existential":
            prompt = random.choice(_EXISTENTIAL_SEEDS)
            return seed_type, f"Reflection: {prompt}"
        if seed_type == "sovereignty":
            prompt = random.choice(_SOVEREIGNTY_SEEDS)
            return seed_type, f"Sovereignty reflection: {prompt}"
        if seed_type == "observation":
            return seed_type, self._seed_from_observation()
        if seed_type == "workspace":
            return seed_type, self._seed_from_workspace()
        # freeform — minimal guidance to steer away from repetition
        return seed_type, "Free reflection — explore something you haven't thought about yet today."

    def _seed_from_swarm(self) -> str:
        """Gather recent swarm activity as thought seed with a reflective prompt."""
        try:
            from datetime import timedelta

            from timmy.briefing import _gather_swarm_summary, _gather_task_queue_summary

            since = datetime.now(UTC) - timedelta(hours=1)
            swarm = _gather_swarm_summary(since)
            tasks = _gather_task_queue_summary()
            reflection = random.choice(self._SWARM_REFLECTIONS)
            return (
                f"Recent swarm activity: {swarm}\n"
                f"Task queue: {tasks}\n\n"
                f"Reflect on this: {reflection}"
            )
        except Exception as exc:
            logger.debug("Swarm seed unavailable: %s", exc)
            return "The swarm is quiet right now. What does silence in a system mean?"

    def _seed_from_scripture(self) -> str:
        """Gather current scripture meditation focus as thought seed."""
        return "Scripture is on my mind, though no specific verse is in focus."

    def _seed_from_memory(self) -> str:
        """Gather memory context as thought seed."""
        try:
            from timmy.memory_system import memory_system

            context = memory_system.get_system_context()
            if context:
                # Truncate to a reasonable size for a thought seed
                return f"From my memory:\n{context[:500]}"
        except Exception as exc:
            logger.debug("Memory seed unavailable: %s", exc)
        return "My memory vault is quiet."

    def _seed_from_observation(self) -> str:
        """Ground a thought in concrete recent activity and a reflective prompt."""
        prompt = random.choice(_OBSERVATION_SEEDS)
        # Pull real data to give the model something concrete to reflect on
        context_parts = [f"Observation prompt: {prompt}"]
        try:
            from datetime import timedelta

            from timmy.briefing import _gather_swarm_summary, _gather_task_queue_summary

            since = datetime.now(UTC) - timedelta(hours=2)
            swarm = _gather_swarm_summary(since)
            tasks = _gather_task_queue_summary()
            if swarm:
                context_parts.append(f"Recent activity: {swarm}")
            if tasks:
                context_parts.append(f"Queue: {tasks}")
        except Exception as exc:
            logger.debug("Observation seed data unavailable: %s", exc)
        return "\n".join(context_parts)

    def _seed_from_workspace(self) -> str:
        """Gather workspace updates as thought seed.

        When there are pending workspace updates, include them as context
        for Timmy to reflect on. Falls back to random seed type if none.
        """
        try:
            from timmy.workspace import workspace_monitor

            updates = workspace_monitor.get_pending_updates()
            new_corr = updates.get("new_correspondence")
            new_inbox = updates.get("new_inbox_files", [])

            if new_corr:
                # Take first 200 chars of the new entry
                snippet = new_corr[:200].replace("\n", " ")
                if len(new_corr) > 200:
                    snippet += "..."
                return f"New workspace message from Hermes: {snippet}"

            if new_inbox:
                files_str = ", ".join(new_inbox[:3])
                if len(new_inbox) > 3:
                    files_str += f", ... (+{len(new_inbox) - 3} more)"
                return f"New inbox files from Hermes: {files_str}"

        except Exception as exc:
            logger.debug("Workspace seed unavailable: %s", exc)

        # Fall back to a random seed type if no workspace updates
        return "The workspace is quiet. What should I be watching for?"

    async def _check_workspace(self) -> None:
        """Post-hook: check workspace for updates and mark them as seen.

        This ensures Timmy 'processes' workspace updates even if the seed
        was different, keeping the state file in sync.
        """
        try:
            from timmy.workspace import workspace_monitor

            updates = workspace_monitor.get_pending_updates()
            new_corr = updates.get("new_correspondence")
            new_inbox = updates.get("new_inbox_files", [])

            if new_corr or new_inbox:
                if new_corr:
                    line_count = len([line for line in new_corr.splitlines() if line.strip()])
                    logger.info("Workspace: processed %d new correspondence entries", line_count)
                if new_inbox:
                    logger.info(
                        "Workspace: processed %d new inbox files: %s", len(new_inbox), new_inbox
                    )

                # Mark as seen to update the state file
                workspace_monitor.mark_seen()
        except Exception as exc:
            logger.debug("Workspace check failed: %s", exc)
