"""Get a value from shared memory.

Shared memory is accessible by all agents - use it for coordination,
shared state, or passing data between agents.

Example:
    # Agent B reads results set by Agent A
    result = await memory.shared_get(key="analysis_results")
    if result["found"]:
        score = result["value"]["score"]
"""

import json
from pathlib import Path

from core.config import get_settings
from core.pathways.context import Context
from core.pathways.models.tool import ToolOutput


async def run(
    key: str,
    *,
    namespace: str = "default",
    context: Context | None = None,
) -> ToolOutput:
    """Get a value from shared memory.

    Args:
        key: Key to retrieve
        namespace: Optional namespace (default: "default")
        context: Execution context (injected by framework)

    Returns
    -------
        {"success": True, "found": True/False, "key": "...", "value": ...}
    """
    if not key:
        return ToolOutput(success=False, error="key is required")

    try:
        state_store = context.services.state_store if context else None

        if not state_store:
            # Fallback to file-based shared memory
            return await _get_file_based(key, namespace)

        # Use StateStore
        value = await state_store.get_shared(key, namespace)

        return ToolOutput(
            success=True,
            data={
                "found": value is not None,
                "key": key,
                "namespace": namespace,
                "value": value,
            },
        )

    except Exception as e:
        return ToolOutput(success=False, error=str(e))


async def _get_file_based(key: str, namespace: str) -> ToolOutput:
    """Fallback to file-based shared memory when StateStore not available."""
    # Using hoisted imports: json, os, Path
    workspace_root = get_settings().workspace_dir
    safe_ns = namespace.replace("/", "_").replace("\\", "_")
    path = Path(workspace_root) / ".albus_store" / "shared" / f"{safe_ns}.json"

    if not path.exists():
        return ToolOutput(
            success=True,
            data={
                "found": False,
                "key": key,
                "namespace": namespace,
                "value": None,
            },
        )

    try:
        memory = json.loads(path.read_text())
        value = memory.get(key)

        return ToolOutput(
            success=True,
            data={
                "found": key in memory,
                "key": key,
                "namespace": namespace,
                "value": value,
            },
        )

    except Exception as e:
        return ToolOutput(success=False, error=str(e))
