"""
handlers/memory.py — Per-target session memory read/write.

Tools: memory_read, memory_write

Memory is stored at:
  mobile_security_mcp/targets/<package>/memory.md
"""

from __future__ import annotations

import logging
from pathlib import Path

logger = logging.getLogger(__name__)

_BASE_DIR = Path(__file__).parent.parent / "targets"

_MEMORY_TEMPLATE = """\
## Target profile
- Package: {package}
- Framework: unknown
- SDK versions: unknown
- Protection tier: unknown

## Confirmed findings
_None yet._

## Tried and failed
_None yet._

## Current hypothesis
_Not yet established._

## Unknowns
- What protection mechanisms are active?
- What is the network communication pattern?
"""


class MemoryHandler:
    """Session memory read/write handler."""

    def _memory_path(self, package: str) -> Path:
        return _BASE_DIR / package / "memory.md"

    def memory_read(self, args: dict) -> dict:
        package = args.get("package", "")
        path = self._memory_path(package)
        if not path.exists():
            # Auto-create from template
            path.parent.mkdir(parents=True, exist_ok=True)
            content = _MEMORY_TEMPLATE.format(package=package)
            path.write_text(content, encoding="utf-8")
        else:
            content = path.read_text(encoding="utf-8")

        return {
            "status": "ok",
            "tool": "memory",
            "output": {
                "package": package,
                "content": content,
                "path": str(path),
            },
        }

    def memory_write(self, args: dict) -> dict:
        package = args.get("package", "")
        content = args.get("content", "")
        path = self._memory_path(package)
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(content, encoding="utf-8")
        return {
            "status": "ok",
            "tool": "memory",
            "output": {"package": package, "path": str(path), "bytes_written": len(content)},
        }
