"""
Storage Module - Apply consolidation decisions to database.

Contains:
- apply_consolidation: Execute a consolidation decision
"""

from typing import Any, Dict

from .models import Cluster, ConsolidationResult


def apply_consolidation(
    store,
    cluster: Cluster,
    decision: Dict[str, Any]
) -> ConsolidationResult:
    """
    Apply a consolidation decision to a cluster.

    Args:
        store: ContextStore instance
        cluster: The cluster being consolidated
        decision: The consolidation decision dict

    Returns:
        ConsolidationResult with details of what was done
    """
    decision_type = decision.get("decision")
    reasoning = decision.get("reasoning", "")

    if decision_type == "keep_one":
        keep_id = decision.get("keep_id")
        if not keep_id:
            return ConsolidationResult(
                cluster_id=cluster.id,
                decision="error",
                reasoning="keep_one decision missing keep_id"
            )

        # Delete all other memories in the cluster (with archival)
        to_delete = [mid for mid in cluster.memory_ids if mid != keep_id]
        for mid in to_delete:
            store.delete_memory(
                mid,
                archive=True,
                deletion_reason="consolidation",
                deletion_source="consolidation_llm",
                replaced_by_id=keep_id,
                cluster_id=cluster.id,
                reasoning=reasoning
            )

        return ConsolidationResult(
            cluster_id=cluster.id,
            decision="keep_one",
            kept_id=keep_id,
            deleted_ids=to_delete,
            reasoning=reasoning
        )

    elif decision_type == "merge":
        merged_type = decision.get("merged_type", "discovery")
        merged_title = decision.get("merged_title")
        merged_fact = decision.get("merged_fact")

        if not merged_title or not merged_fact:
            return ConsolidationResult(
                cluster_id=cluster.id,
                decision="error",
                reasoning="merge decision missing merged_title or merged_fact"
            )

        # Combine files from all memories
        all_files = set()
        for mem in cluster.memories:
            all_files.update(mem.get("files", []))

        # Find newest timestamp from cluster memories
        timestamps = [mem.get("created_at", "") for mem in cluster.memories if mem.get("created_at")]
        newest_timestamp = max(timestamps) if timestamps else None

        # Add the consolidated memory with preserved timestamp
        result = store.add_consolidated_memory(
            obs_type=merged_type,
            title=merged_title,
            fact=merged_fact,
            files=list(all_files),
            source_ids=cluster.memory_ids,
            created_at=newest_timestamp
        )

        # Delete all original memories (with archival)
        merged_memory_id = result["id"]
        for mid in cluster.memory_ids:
            store.delete_memory(
                mid,
                archive=True,
                deletion_reason="consolidation",
                deletion_source="consolidation_llm",
                replaced_by_id=merged_memory_id,
                cluster_id=cluster.id,
                reasoning=reasoning
            )

        return ConsolidationResult(
            cluster_id=cluster.id,
            decision="merge",
            merged_memory={
                "id": result["id"],
                "type": merged_type,
                "title": merged_title,
                "fact": merged_fact,
                "files": list(all_files)
            },
            deleted_ids=cluster.memory_ids,
            reasoning=reasoning
        )

    elif decision_type == "keep_all":
        return ConsolidationResult(
            cluster_id=cluster.id,
            decision="keep_all",
            reasoning=reasoning
        )

    else:
        return ConsolidationResult(
            cluster_id=cluster.id,
            decision="error",
            reasoning=f"Unknown decision type: {decision_type}"
        )
