"""
Feedback Aggregator REST API Blueprint

PRD §6 — Inspector API endpoints:
    GET /inspector/task-trace?task_id=xxx          (§6.1)
    GET /inspector/memory-profile?memory_id=xxx    (§6.2)
    GET /inspector/metrics                         (§6.3)
    GET /inspector/timeline?task_id=xxx            (§6.4)

Additional endpoints:
    GET /inspector/top-memories?n=10
    GET /inspector/noisy-memories?min_noise=3
    GET /inspector/snapshot?task_id=xxx
    GET /inspector/metrics/window?since=<unix>&until=<unix>
"""

import time
import logging
from flask import Blueprint, request, jsonify
from openmemo.feedback_aggregator import FeedbackAggregator
from openmemo.memory_feedback import FeedbackStore

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


def create_aggregator_blueprint(db_path: str = "openmemo.db") -> Blueprint:
    bp = Blueprint("feedback_aggregator", __name__)
    store = FeedbackStore(db_path=db_path)
    agg = FeedbackAggregator(store)

    # ── GET /inspector/task-trace ─────────────────────────────────────────────
    @bp.route("/inspector/task-trace", methods=["GET"])
    def task_trace():
        """PRD §6.1 — Task chain trace for Inspector."""
        task_id = request.args.get("task_id", "").strip()
        if not task_id:
            return jsonify({"error": "task_id required"}), 400
        t0 = time.time()
        trace = agg.task_trace(task_id)
        trace["api_ms"] = round((time.time() - t0) * 1000, 1)
        return jsonify(trace)

    # ── GET /inspector/memory-profile ────────────────────────────────────────
    @bp.route("/inspector/memory-profile", methods=["GET"])
    def memory_profile():
        """PRD §6.2 — Memory quality profile for Inspector."""
        memory_id = request.args.get("memory_id", "").strip()
        if not memory_id:
            return jsonify({"error": "memory_id required"}), 400
        t0 = time.time()
        profile = agg.memory_profile(memory_id)
        profile["api_ms"] = round((time.time() - t0) * 1000, 1)
        return jsonify(profile)

    # ── GET /inspector/metrics ────────────────────────────────────────────────
    @bp.route("/inspector/metrics", methods=["GET"])
    def metrics():
        """PRD §6.3 — Global impact metrics for Inspector header."""
        t0 = time.time()
        data = agg.impact_metrics()
        data["api_ms"] = round((time.time() - t0) * 1000, 1)
        return jsonify(data)

    # ── GET /inspector/timeline ───────────────────────────────────────────────
    @bp.route("/inspector/timeline", methods=["GET"])
    def timeline():
        """PRD §6.4 — Event timeline for Inspector."""
        task_id   = request.args.get("task_id", "").strip() or None
        memory_id = request.args.get("memory_id", "").strip() or None
        limit     = int(request.args.get("limit", 100))
        t0 = time.time()
        events = agg.timeline(task_id=task_id, memory_id=memory_id, limit=limit)
        return jsonify({
            "events": events,
            "count": len(events),
            "api_ms": round((time.time() - t0) * 1000, 1),
        })

    # ── GET /inspector/top-memories ───────────────────────────────────────────
    @bp.route("/inspector/top-memories", methods=["GET"])
    def top_memories():
        n         = int(request.args.get("n", 10))
        min_usage = int(request.args.get("min_usage", 1))
        t0 = time.time()
        profiles = agg.top_memories(n=n, min_usage=min_usage)
        return jsonify({
            "memories": profiles,
            "count": len(profiles),
            "api_ms": round((time.time() - t0) * 1000, 1),
        })

    # ── GET /inspector/noisy-memories ────────────────────────────────────────
    @bp.route("/inspector/noisy-memories", methods=["GET"])
    def noisy_memories():
        min_noise = int(request.args.get("min_noise", 3))
        t0 = time.time()
        profiles = agg.noisy_memories(min_noise=min_noise)
        return jsonify({
            "memories": profiles,
            "count": len(profiles),
            "api_ms": round((time.time() - t0) * 1000, 1),
        })

    # ── GET /inspector/snapshot ───────────────────────────────────────────────
    @bp.route("/inspector/snapshot", methods=["GET"])
    def snapshot():
        """Full Inspector snapshot combining all 4 outputs."""
        task_id = request.args.get("task_id", "").strip() or None
        t0 = time.time()
        snap = agg.inspector_snapshot(task_id=task_id)
        snap["api_ms"] = round((time.time() - t0) * 1000, 1)
        return jsonify(snap)

    # ── GET /inspector/metrics/window ────────────────────────────────────────
    @bp.route("/inspector/metrics/window", methods=["GET"])
    def metrics_window():
        """Build metrics for a time window. since/until as Unix timestamps."""
        since_ts = float(request.args.get("since", 0))
        until_ts_raw = request.args.get("until")
        until_ts = float(until_ts_raw) if until_ts_raw else None
        if not since_ts:
            return jsonify({"error": "since timestamp required"}), 400
        t0 = time.time()
        data = agg.impact_metrics_window(since_ts, until_ts)
        data["api_ms"] = round((time.time() - t0) * 1000, 1)
        return jsonify(data)

    return bp
