"""
AI Prompts Routes
Blueprint exposing centrally managed prompts so the Flutter app can load
system / user prompts dynamically — no app rebuild required to update prompts.

Endpoints:
  GET  /api/ai/prompts/system  — single system prompt by mode + context
  POST /api/ai/prompts/user    — single user prompt by mode
  POST /api/ai/prompts/bulk    — many prompts in one call (for prefetch)
  GET  /api/ai/prompts/list    — list all available modes and contexts
"""

import logging
import sys
import os

from flask import Blueprint, request, jsonify

# Resolve project root so we can import sibling modules
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from utils import require_api_key
from ai_prompts import get_system_prompt, get_user_prompt, list_all_modes, list_all_contexts

logger = logging.getLogger(__name__)

ai_prompts_bp = Blueprint('ai_prompts', __name__)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _ok(payload: dict, status: int = 200):
    return jsonify({'status': 'success', **payload}), status


def _err(message: str, status: int = 400):
    return jsonify({'status': 'error', 'message': message}), status


# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------

@ai_prompts_bp.route('/api/ai/prompts/system', methods=['GET'])
@require_api_key
def route_get_system_prompt():
    """
    Retrieve the system prompt for a specific mode + context combination.

    Query params
    ------------
    mode    : str  — e.g. summary | explain | simplify | quizGeneration …
    context : str  — e.g. notes | quizDetail | analytics | qaSession …
    """
    mode    = request.args.get('mode', '').strip()
    context = request.args.get('context', '').strip()

    if not mode or not context:
        return _err('Both "mode" and "context" query parameters are required.', 400)

    prompt = get_system_prompt(mode, context)

    if prompt is None:
        return _err(
            f'No system prompt found for mode="{mode}", context="{context}". '
            f'Available contexts: {list_all_contexts()}',
            404,
        )

    return _ok({'prompt': prompt, 'mode': mode, 'context': context})


@ai_prompts_bp.route('/api/ai/prompts/user', methods=['POST'])
@require_api_key
def route_get_user_prompt():
    """
    Retrieve the user-turn prompt template for a specific mode.
    Optionally substitutes {content} if 'content' is provided.

    Request JSON
    ------------
    mode    : str              — AI mode key
    content : str (optional)  — Content to embed in the prompt
    """
    data    = request.get_json(silent=True) or {}
    mode    = data.get('mode', '').strip()
    content = data.get('content', '')

    if not mode:
        return _err('"mode" is required in the request body.', 400)

    prompt = get_user_prompt(mode, content)

    return _ok({'prompt': prompt, 'mode': mode})


@ai_prompts_bp.route('/api/ai/prompts/bulk', methods=['POST'])
@require_api_key
def route_get_bulk_prompts():
    """
    Retrieve system + user prompts for multiple mode/context combinations
    in a single request — ideal for app startup prefetching.

    Request JSON
    ------------
    modes    : list[str]  — list of mode keys  (default: common set)
    contexts : list[str]  — list of context keys (default: common set)

    Response
    --------
    {
      "prompts": {
        "<context>": {
          "<mode>": { "system": "...", "user": "..." }
        }
      }
    }
    """
    data     = request.get_json(silent=True) or {}
    modes    = data.get('modes',    ['summary', 'explain', 'simplify', 'quizGeneration', 'examples'])
    contexts = data.get('contexts', ['notes', 'quizDetail', 'analytics', 'qaSession'])

    # Sanitise inputs — only allow strings, max 10 of each
    modes    = [str(m).strip() for m in modes    if isinstance(m, str)][:10]
    contexts = [str(c).strip() for c in contexts if isinstance(c, str)][:10]

    result: dict = {}
    for ctx in contexts:
        result[ctx] = {}
        for mode in modes:
            system = get_system_prompt(mode, ctx)
            user   = get_user_prompt(mode)
            if system or user:
                result[ctx][mode] = {
                    'system': system,
                    'user':   user,
                }

    return _ok({'prompts': result})


@ai_prompts_bp.route('/api/ai/prompts/list', methods=['GET'])
@require_api_key
def route_list_prompts():
    """
    List all available modes and contexts so the Flutter app can
    discover what prompt combinations are supported.
    """
    return _ok({
        'modes':    list_all_modes(),
        'contexts': list_all_contexts(),
    })
