import json
import time
from pathlib import Path
from typing import List, Dict, Any, Optional
from health.utils.logging_config import setup_logger
from health import config

logger = setup_logger(__name__)

CONTEXT_DIR = config.DATA_DIR / "slack_context"
CONTEXT_DIR.mkdir(parents=True, exist_ok=True)

class ContextStorage:
    """Manages persistent conversation history for Slack channels."""

    # Maximum messages to keep (simple sliding window)
    MAX_MESSAGES = 40

    def __init__(self, channel_id: str):
        self.channel_id = channel_id
        self.file_path = CONTEXT_DIR / f"{channel_id}.json"

    def _load(self) -> List[Dict[str, Any]]:
        if not self.file_path.exists():
            return []
        try:
            with open(self.file_path, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception as e:
            logger.error(f"Failed to load context for {self.channel_id}: {e}")
            return []

    def _save(self, context: List[Dict[str, Any]]) -> None:
        try:
            with open(self.file_path, "w", encoding="utf-8") as f:
                json.dump(context, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.error(f"Failed to save context for {self.channel_id}: {e}")

    def add_message(self, role: str, content: str, model: Optional[str] = None) -> None:
        """
        Add a message to the context.

        Args:
            role: 'user' or 'assistant'
            content: Message content
            model: Model identifier (only for assistant messages, currently always 'gemini')
        """
        context = self._load()
        msg = {
            "role": role,
            "content": content,
            "timestamp": time.time()
        }
        if model:
            msg["model"] = model

        context.append(msg)

        # Apply sliding window compression
        if len(context) > self.MAX_MESSAGES:
            context = context[-self.MAX_MESSAGES:]

        self._save(context)

    def get_context(self) -> List[Dict[str, Any]]:
        """
        Get conversation context in standard format.

        Returns messages as [{"role": "user", "content": "..."}, ...]
        """
        full_context = self._load()

        # Convert to standard format (remove timestamp and model metadata)
        filtered = []
        for msg in full_context:
            filtered.append({
                "role": msg["role"],
                "content": msg["content"]
            })

        return filtered

    def clear(self) -> None:
        """Clear all context for this channel."""
        if self.file_path.exists():
            self.file_path.unlink()
        logger.info(f"Cleared context for {self.channel_id}")
