"""Memory CRUD endpoints."""

from __future__ import annotations

from aiohttp import web


async def list_memories(request: web.Request) -> web.Response:
    store = request.app["store"]
    mem_type = request.rel_url.query.get("type")
    query = request.rel_url.query.get("query")
    if query:
        memories = await store.search_memories(query=query, type=mem_type)
    else:
        memories = await store.list_memories(type=mem_type)
    return web.json_response(memories)


async def get_memory(request: web.Request) -> web.Response:
    store = request.app["store"]
    key = request.match_info["key"]
    memory = await store.get_memory(key)
    if memory is None:
        raise web.HTTPNotFound(reason=f"Memory not found: {key}")
    return web.json_response(memory)


async def save_memory(request: web.Request) -> web.Response:
    try:
        body = await request.json()
    except Exception as exc:
        raise web.HTTPBadRequest(reason=f"Invalid JSON: {exc}") from exc
    key = body.get("key")
    value = body.get("value")
    if not key or not value:
        raise web.HTTPBadRequest(reason="'key' and 'value' are required")
    mem_type = body.get("type", "general")
    if mem_type not in ("general", "feedback", "project", "user", "reference", "preference"):
        raise web.HTTPBadRequest(reason=f"Invalid memory type: {mem_type}")
    store = request.app["store"]
    result = await store.save_memory(key, value, mem_type)
    return web.json_response(result, status=201)


async def delete_memory(request: web.Request) -> web.Response:
    store = request.app["store"]
    key = request.match_info["key"]
    deleted = await store.delete_memory(key)
    if not deleted:
        raise web.HTTPNotFound(reason=f"Memory not found: {key}")
    return web.json_response({"deleted": key})
