import logging
from soagila.core.mae.models import Conflict, ConflictType, ArbitrationResult

logger = logging.getLogger("soagila.mae.strategies")


# =============================================
# TIER WEIGHT PROFILES PER TASK CONTEXT
# =============================================

TASK_TIER_WEIGHTS = {
    "customer_service": {
        "working": 0.6,    # Current state matters most
        "episodic": 0.3,   # Recent interactions
        "semantic": 0.1,   # Background patterns
    },
    "strategic_analysis": {
        "working": 0.1,    # Current state less relevant
        "episodic": 0.3,   # Specific events for evidence
        "semantic": 0.6,   # Long-term patterns matter most
    },
    "compliance_audit": {
        "working": 0.33,   # All tiers equally important
        "episodic": 0.34,  # Full transparency
        "semantic": 0.33,
    },
    "general": {
        "working": 0.4,
        "episodic": 0.35,
        "semantic": 0.25,
    },
}


def get_tier_weights(task_context: str) -> dict[str, float]:
    """Get tier priority weights for a given task context."""
    return TASK_TIER_WEIGHTS.get(task_context, TASK_TIER_WEIGHTS["general"])


# =============================================
# RESOLUTION STRATEGIES
# =============================================

def resolve_contradiction(
    conflict: Conflict,
    task_context: str,
    working_content: str,
    episodic_content: str,
    semantic_content: str,
) -> dict:
    """
    Resolve a direct contradiction between tiers.
    Winner determined by task context.
    """
    weights = get_tier_weights(task_context)

    # Determine winner based on weights
    tier_scores = {
        "working": weights["working"],
        "episodic": weights["episodic"],
        "semantic": weights["semantic"],
    }

    # Boost the tiers involved in the conflict
    for tier in [conflict.memory_a_tier, conflict.memory_b_tier]:
        if tier in tier_scores:
            tier_scores[tier] *= 1.5

    winner_tier = max(tier_scores, key=tier_scores.get)
    winner_content = {
        "working": working_content,
        "episodic": episodic_content,
        "semantic": semantic_content,
    }.get(winner_tier, "")

    return {
        "strategy": "task_priority",
        "winner_tier": winner_tier,
        "winner_content": winner_content,
        "tier_scores": tier_scores,
        "explanation": (
            f"Contradiction detected between {conflict.memory_a_tier} and "
            f"{conflict.memory_b_tier} tiers. For '{task_context}' context, "
            f"{winner_tier} tier takes priority. "
            f"{conflict.memory_a_tier}: \"{conflict.memory_a_content[:80]}...\" vs "
            f"{conflict.memory_b_tier}: \"{conflict.memory_b_content[:80]}...\""
        ),
    }


def resolve_tension(
    conflict: Conflict,
    task_context: str,
) -> dict:
    """
    Resolve tension — not contradictory but implying different strategies.
    Uses weighted synthesis to combine both perspectives.
    """
    weights = get_tier_weights(task_context)

    weight_a = weights.get(conflict.memory_a_tier, 0.33)
    weight_b = weights.get(conflict.memory_b_tier, 0.33)

    # Normalize weights
    total = weight_a + weight_b
    weight_a /= total
    weight_b /= total

    return {
        "strategy": "weighted_synthesis",
        "synthesis_weights": {
            conflict.memory_a_tier: round(weight_a, 3),
            conflict.memory_b_tier: round(weight_b, 3),
        },
        "explanation": (
            f"Tension detected between {conflict.memory_a_tier} "
            f"({weight_a:.0%} weight) and {conflict.memory_b_tier} "
            f"({weight_b:.0%} weight). Both perspectives synthesized: "
            f"\"{conflict.memory_a_content[:60]}...\" combined with "
            f"\"{conflict.memory_b_content[:60]}...\""
        ),
    }


def resolve_temporal_sequence(
    conflict: Conflict,
) -> dict:
    """
    Resolve temporal sequence — information from different time periods.
    Present as a timeline highlighting changes.
    """
    return {
        "strategy": "temporal_analysis",
        "explanation": (
            f"Temporal sequence detected: {conflict.memory_a_tier} tier has "
            f"earlier information while {conflict.memory_b_tier} tier has "
            f"more recent data. Both preserved in timeline order. "
            f"Earlier: \"{conflict.memory_a_content[:60]}...\" → "
            f"Later: \"{conflict.memory_b_content[:60]}...\""
        ),
    }
