"""
Context Memory REST API Blueprint

PRD §9 + §12 — API Design:
    POST   /context/message         — Add a message to a session
    POST   /context/event           — Add a timeline event
    POST   /context/complete        — Trigger task completion + summarization
    GET    /context/recall          — Progressive recall for a session
    GET    /context/sessions        — List sessions for a user
    DELETE /context/session/{id}    — Delete a session
"""

import time
import logging
from flask import Blueprint, request, jsonify
from openmemo.context_memory import ContextMemory

logger = logging.getLogger("openmemo.context_memory.api")


def create_context_blueprint(db_path: str = "openmemo.db",
                              max_tokens: int = 800) -> Blueprint:
    bp = Blueprint("context_memory", __name__)
    cm = ContextMemory(db_path=db_path, max_tokens=max_tokens)

    # ── POST /context/message ─────────────────────────────────────────────────
    @bp.route("/context/message", methods=["POST"])
    def add_message():
        """
        Record a message to a session.

        Body: { "session_id": "...", "role": "user|assistant|tool",
                "content": "...", "user_id": "" }
        """
        body = request.get_json(silent=True) or {}
        session_id = body.get("session_id", "").strip()
        role = body.get("role", "user").strip()
        content = body.get("content", "").strip()
        user_id = body.get("user_id", "")

        if not session_id:
            return jsonify({"error": "session_id required"}), 400
        if not content:
            return jsonify({"error": "content required"}), 400
        if role not in ("user", "assistant", "tool"):
            role = "user"

        t0 = time.time()
        mid = cm.add_message(session_id, role, content, user_id=user_id)
        return jsonify({
            "status": "recorded",
            "message_id": mid,
            "session_id": session_id,
            "latency_ms": round((time.time() - t0) * 1000, 1),
        }), 201

    # ── POST /context/event ───────────────────────────────────────────────────
    @bp.route("/context/event", methods=["POST"])
    def add_event():
        """
        Record a timeline event.

        Body: { "session_id": "...", "type": "decision|action|result|error",
                "content": "..." }
        """
        body = request.get_json(silent=True) or {}
        session_id = body.get("session_id", "").strip()
        event_type = body.get("type", "action").strip()
        content = body.get("content", "").strip()

        if not session_id:
            return jsonify({"error": "session_id required"}), 400
        if not content:
            return jsonify({"error": "content required"}), 400

        t0 = time.time()
        eid = cm.add_event(session_id, event_type, content)
        return jsonify({
            "status": "recorded",
            "event_id": eid,
            "session_id": session_id,
            "latency_ms": round((time.time() - t0) * 1000, 1),
        }), 201

    # ── POST /context/complete ─────────────────────────────────────────────────
    @bp.route("/context/complete", methods=["POST"])
    def task_complete():
        """
        Trigger task completion: records result + generates summary.

        Body: { "session_id": "...", "task": "...", "result": "..." }
        """
        body = request.get_json(silent=True) or {}
        session_id = body.get("session_id", "").strip()
        task = body.get("task", "")
        result = body.get("result", "")

        if not session_id:
            return jsonify({"error": "session_id required"}), 400

        t0 = time.time()
        session = cm.on_task_complete(session_id, task=task, result=result)
        return jsonify({
            "status": "summarized",
            "session_id": session_id,
            "summary": session.summary,
            "latency_ms": round((time.time() - t0) * 1000, 1),
        })

    # ── GET /context/recall ───────────────────────────────────────────────────
    @bp.route("/context/recall", methods=["GET"])
    def recall():
        """
        Progressive recall for a session.

        Query params:
            session_id  — required
            level       — 1 (summary), 2 (+ timeline), 3 (+ raw). Default: auto
            format      — "text" (default) | "json"
        """
        session_id = request.args.get("session_id", "").strip()
        level = request.args.get("level", "auto")
        fmt = request.args.get("format", "text")

        if not session_id:
            return jsonify({"error": "session_id required"}), 400

        t0 = time.time()

        if fmt == "json":
            data = cm.to_dict(session_id)
            data["latency_ms"] = round((time.time() - t0) * 1000, 1)
            return jsonify(data)

        if level == "auto":
            block = cm.inject(session_id)
        else:
            block = cm.recall(session_id, level=int(level))

        return jsonify({
            "session_id": session_id,
            "context_block": block,
            "latency_ms": round((time.time() - t0) * 1000, 1),
        })

    # ── GET /context/sessions ─────────────────────────────────────────────────
    @bp.route("/context/sessions", methods=["GET"])
    def list_sessions():
        """
        List sessions for a user.

        Query params: user_id (optional)
        """
        user_id = request.args.get("user_id", "")
        sessions = cm.list_sessions(user_id=user_id)
        return jsonify({
            "user_id": user_id,
            "sessions": [s.to_dict() for s in sessions],
            "count": len(sessions),
        })

    # ── DELETE /context/session/<id> ──────────────────────────────────────────
    @bp.route("/context/session/<session_id>", methods=["DELETE"])
    def delete_session(session_id: str):
        """Delete a session and all its data."""
        cm.delete_session(session_id)
        return jsonify({"status": "deleted", "session_id": session_id})

    return bp
