from __future__ import annotations

from armorer.agent_sdk import tool
from armorer.core.memory_retrieval import recall_relevant_memory
from armorer.core.memory_schema import DurableMemoryRecord, MemoryKind
from armorer.core.memory_store import list_memory_records, upsert_memory_record


@tool(category="memory", verification_level="durable_memory", safe_for_retrieval=True)
def recall_memory_facts(task_type: str = "general", app_alias: str = "") -> list[dict]:
    """Return relevant durable Armorer memory facts for a task type and optional app alias."""
    prompt = " ".join(part for part in [task_type, app_alias] if str(part).strip())
    return recall_relevant_memory(prompt=prompt, installed_agents=[{"alias": app_alias, "agent_id": app_alias}] if app_alias else [])


@tool(category="memory", verification_level="durable_memory", safe_for_retrieval=True)
def list_durable_memory() -> list[dict]:
    """Return non-expired durable Armorer memory records."""
    return [record.model_dump(mode="json") for record in list_memory_records()]


@tool(category="memory", verification_level="verified_write")
def store_verified_memory(subject: str, value: dict, kind: str = "runtime_fact", scope: str = "global", tags: list[str] | None = None) -> dict:
    """Store a verified durable Armorer memory record."""
    record = DurableMemoryRecord(
        kind=MemoryKind(kind),
        subject=str(subject or "").strip() or "memory",
        value=dict(value or {}),
        source="tool_store_verified_memory",
        verified=True,
        created_at=__import__("time").time(),
        scope=str(scope or "global").strip() or "global",
        tags=[str(tag).strip() for tag in (tags or []) if str(tag).strip()],
    )
    return upsert_memory_record(record).model_dump(mode="json")
