"""Context manager for actor-first CLI sessions (ported from v2)."""

from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path
from typing import Any


class ContextManager:
    """Manages conversation context for CLI sessions."""

    def __init__(self, context_name: str, context_dir: Path | None = None):
        self.context_name = context_name
        if context_dir is None:
            home_dir = Path.home()
            self.context_dir = home_dir / ".cleveragents" / "context" / context_name
        else:
            self.context_dir = Path(context_dir) / context_name
        self.context_dir.mkdir(parents=True, exist_ok=True)
        self.messages_file = self.context_dir / "messages.json"
        self.metadata_file = self.context_dir / "metadata.json"
        self.state_file = self.context_dir / "state.json"
        self.global_context_file = self.context_dir / "global_context.json"
        self.messages: list[dict[str, Any]] = self._load_messages()
        self.metadata: dict[str, Any] = self._load_metadata()
        self.state: dict[str, Any] = self._load_state()
        self.global_context: dict[str, Any] = self._load_global_context()

    def _load_messages(self) -> list[dict[str, Any]]:
        if self.messages_file.exists():
            try:
                with open(self.messages_file, encoding="utf-8") as f:
                    return json.load(f)
            except (OSError, json.JSONDecodeError):
                return []
        return []

    def _load_metadata(self) -> dict[str, Any]:
        if self.metadata_file.exists():
            try:
                with open(self.metadata_file, encoding="utf-8") as f:
                    return json.load(f)
            except (OSError, json.JSONDecodeError):
                return {}
        return {
            "created_at": datetime.now().isoformat(),
            "last_updated": datetime.now().isoformat(),
            "context_name": self.context_name,
        }

    def _load_state(self) -> dict[str, Any]:
        if self.state_file.exists():
            try:
                with open(self.state_file, encoding="utf-8") as f:
                    return json.load(f)
            except (OSError, json.JSONDecodeError):
                return {}
        return {}

    def _load_global_context(self) -> dict[str, Any]:
        if self.global_context_file.exists():
            try:
                with open(self.global_context_file, encoding="utf-8") as f:
                    return json.load(f)
            except (OSError, json.JSONDecodeError):
                return {}
        return {}

    def save(self) -> None:
        self.metadata["last_updated"] = datetime.now().isoformat()
        self.metadata["message_count"] = len(self.messages)
        with open(self.messages_file, "w", encoding="utf-8") as f:
            json.dump(self.messages, f, indent=2)
        with open(self.metadata_file, "w", encoding="utf-8") as f:
            json.dump(self.metadata, f, indent=2)
        with open(self.state_file, "w", encoding="utf-8") as f:
            json.dump(self.state, f, indent=2)
        with open(self.global_context_file, "w", encoding="utf-8") as f:
            json.dump(self.global_context, f, indent=2)

    def add_message(
        self, role: str, content: str, metadata: dict[str, Any] | None = None
    ) -> None:
        message = {
            "role": role,
            "content": content,
            "timestamp": datetime.now().isoformat(),
            "metadata": metadata or {},
        }
        self.messages.append(message)
        self.save()

    def get_conversation_history(self) -> list[dict[str, Any]]:
        return self.messages

    def get_last_n_messages(self, n: int = 10) -> list[dict[str, Any]]:
        return self.messages[-n:] if self.messages else []

    def clear(self) -> None:
        self.messages = []
        self.state = {}
        self.global_context = {}
        self.metadata = {
            "created_at": datetime.now().isoformat(),
            "last_updated": datetime.now().isoformat(),
            "context_name": self.context_name,
        }
        self.save()

    def delete(self) -> None:
        import shutil

        if self.context_dir.exists():
            shutil.rmtree(self.context_dir)

    def update_state(self, key: str, value: Any) -> None:
        self.state[key] = value
        self.save()

    def update_metadata(self, updates: dict[str, Any]) -> None:
        self.metadata.update(updates)
        self.metadata["last_updated"] = datetime.now().isoformat()
        self.save()

    def get_state(self, key: str, default: Any = None) -> Any:
        return self.state.get(key, default)

    def exists(self) -> bool:
        return self.context_dir.exists() and self.messages_file.exists()

    def save_global_context(self, global_context: dict[str, Any]) -> None:
        self.global_context = global_context
        with open(self.global_context_file, "w", encoding="utf-8") as f:
            json.dump(self.global_context, f, indent=2)

    def get_global_context(self) -> dict[str, Any]:
        return self.global_context

    def export_context(self, export_file: Path) -> None:
        """Export the context data to a JSON file."""
        data = {
            "context_name": self.context_name,
            "messages": self.messages,
            "metadata": self.metadata,
            "state": self.state,
            "global_context": self.global_context,
        }
        export_file.parent.mkdir(parents=True, exist_ok=True)
        with open(export_file, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2)

    def import_context(self, context_file: Path) -> None:
        with open(context_file, encoding="utf-8") as f:
            data = json.load(f)
        self.messages = data.get("messages", [])
        self.metadata = data.get("metadata", self._load_metadata())
        self.state = data.get("state", {})
        self.global_context = data.get("global_context", {})
        self.save()
