"""
Memory Orchestrator REST API Blueprint

PRD §4 — Input/Output:
    POST /orchestrate      — Full orchestration pipeline
    GET  /orchestrate/classify  — Classify a task string
    GET  /orchestrate/budget    — Show token budget for a task type
"""

import time
import logging
from flask import Blueprint, request, jsonify
from openmemo.memory_orchestrator import MemoryOrchestrator

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


def create_orchestrator_blueprint(db_path: str = "openmemo.db",
                                   max_tokens: int = 2000) -> Blueprint:
    bp = Blueprint("memory_orchestrator", __name__)
    orch = MemoryOrchestrator(db_path=db_path, max_tokens=max_tokens)

    # ── POST /orchestrate ─────────────────────────────────────────────────────
    @bp.route("/orchestrate", methods=["POST"])
    def orchestrate():
        """
        Full orchestration pipeline.

        Body (PRD §4 input):
        {
            "task":       "deploy backend",
            "agent_role": "coding",
            "task_type":  "deployment",   (optional override)
            "user_id":    "u123",
            "session_id": "s123",
            "agent_id":   "agent1",
            "team_id":    "",
            "user_input": ""              (defaults to task)
        }

        Returns PRD §4 output + orchestration metadata.
        """
        body = request.get_json(silent=True) or {}
        task = body.get("task", "").strip()
        if not task:
            return jsonify({"error": "task required"}), 400

        t0 = time.time()
        result = orch.build_prompt(
            task=task,
            user_id=body.get("user_id", ""),
            session_id=body.get("session_id", ""),
            agent_id=body.get("agent_id", ""),
            team_id=body.get("team_id", ""),
            agent_role=body.get("agent_role", ""),
            task_type=body.get("task_type", ""),
            mode=body.get("mode", ""),
            system_block=body.get("system_block", ""),
            user_input=body.get("user_input", ""),
        )
        result["api_latency_ms"] = round((time.time() - t0) * 1000, 1)
        return jsonify(result)

    # ── GET /orchestrate/classify ─────────────────────────────────────────────
    @bp.route("/orchestrate/classify", methods=["GET"])
    def classify():
        """
        Classify a task string.

        Query params: task, agent_role (optional)
        """
        task = request.args.get("task", "").strip()
        agent_role = request.args.get("agent_role", "")
        if not task:
            return jsonify({"error": "task required"}), 400

        task_type = orch.classify(task, agent_role)
        mode = orch.get_mode(task_type)
        return jsonify({
            "task": task,
            "task_type": task_type,
            "mode": mode,
        })

    # ── GET /orchestrate/budget ───────────────────────────────────────────────
    @bp.route("/orchestrate/budget", methods=["GET"])
    def budget():
        """
        Show token budget allocation for a task type.

        Query params: task_type (default: coding)
        """
        task_type = request.args.get("task_type", "coding")
        from openmemo.memory_orchestrator.budget_allocator import BudgetAllocator
        allocator = BudgetAllocator(max_tokens=max_tokens)
        alloc = allocator.allocate(task_type)
        return jsonify({
            "task_type": task_type,
            "max_tokens": max_tokens,
            "allocation": alloc,
            "total": sum(alloc.values()),
        })

    return bp
