"""
Memory Ranker — Priority ordering across memory layers.

PRD §7 — Memory Priority Strategy:
    Default order: user_memory > context > task_memory > team_memory > experience

PRD §11 — Mode Switching:
    exploration:  context ↑, experience ↓
    execution:    experience ↑, context ↓
    debug:        context ↑, task_memory ↑

PRD §10 — Final prompt structure order:
    USER PROFILE → CONTEXT SUMMARY → TASK MEMORY → EXPERIENCE → USER INPUT
"""

import logging
from typing import List, Dict

logger = logging.getLogger("openmemo.orchestrator")

MEMORY_LAYERS = [
    "user_memory",
    "context",
    "task_memory",
    "team_memory",
    "experience",
]

# Base priority scores (higher = more important = injected first)
_BASE_PRIORITY = {
    "user_memory": 5,
    "context":     4,
    "task_memory": 3,
    "team_memory": 2,
    "experience":  1,
}

# Mode adjustments — delta applied to base priority
_MODE_ADJUSTMENTS: Dict[str, Dict[str, int]] = {
    "exploration": {
        "context":    +3,   # context ↑
        "experience": -2,   # experience ↓
    },
    "execution": {
        "experience": +3,   # experience ↑
        "context":    -2,   # context ↓
    },
    "debug": {
        "context":     +3,  # context ↑
        "task_memory": +2,  # task_memory ↑
        "experience":  -1,
    },
    "default": {},
}

# Task type → mode mapping (PRD §11 + §8)
_TASK_TO_MODE = {
    "debugging":  "debug",
    "deployment": "execution",
    "coding":     "execution",
    "planning":   "exploration",
    "research":   "exploration",
}


class MemoryRanker:
    """
    Ranks memory layers by priority for a given task type / mode.

    Usage:
        ranker = MemoryRanker()
        ordered = ranker.rank(task_type="deployment")
        # → ["user_memory", "experience", "context", "task_memory", "team_memory"]
    """

    def rank(self, task_type: str = "coding",
             mode: str = "") -> List[str]:
        """
        Return memory layers sorted by priority (highest first).

        mode overrides task_type if provided explicitly.
        """
        effective_mode = mode or _TASK_TO_MODE.get(task_type, "default")
        adjustments = _MODE_ADJUSTMENTS.get(effective_mode, {})

        scores = {}
        for layer in MEMORY_LAYERS:
            scores[layer] = _BASE_PRIORITY[layer] + adjustments.get(layer, 0)

        ordered = sorted(MEMORY_LAYERS, key=lambda l: scores[l], reverse=True)
        logger.debug("rank task=%s mode=%s → %s", task_type, effective_mode, ordered)
        return ordered

    def get_mode(self, task_type: str) -> str:
        return _TASK_TO_MODE.get(task_type, "default")

    def priority_scores(self, task_type: str = "coding",
                        mode: str = "") -> Dict[str, int]:
        """Return raw priority scores for debugging/testing."""
        effective_mode = mode or _TASK_TO_MODE.get(task_type, "default")
        adjustments = _MODE_ADJUSTMENTS.get(effective_mode, {})
        return {l: _BASE_PRIORITY[l] + adjustments.get(l, 0) for l in MEMORY_LAYERS}
