"""V1 API routes - Legacy implementation."""
from __future__ import annotations

import time
from flask import Blueprint, jsonify, request
from concurrent.futures import ThreadPoolExecutor

from lawrisk.services.lawrisk_service import (
    search_subjects,
    search_subjects_llm,
    suggest_questions_embed,
)

v1_bp = Blueprint('lawrisk_v1', __name__, url_prefix='/fs-ai-asistant/api/workflow/lawrisk')


@v1_bp.route('', methods=['POST', 'GET'])
def lawrisk_search():
    """V1 search endpoint - legacy API."""
    query, debug_flag, top_k_int, mode, _region_filter = _extract_params()

    if not query or not isinstance(query, str):
        return jsonify({"error": "query is required"}), 400

    try:
        t0 = time.time()
        with ThreadPoolExecutor(max_workers=3) as ex:
            fut_ret = ex.submit(
                search_subjects if mode == "embed" else search_subjects_llm,
                query,
                debug_flag,
                top_k_int,
            )
            fut_qs = ex.submit(suggest_questions_embed, query, max(1, top_k_int))

            result = fut_ret.result()
            rec_questions = fut_qs.result() or []

        if debug_flag and isinstance(result, dict) and "debug" in result:
            dbg = result["debug"]
            model = dbg.get("model") or "embed"
            print(f"[LAWRISK-DEBUG] mode={model}")

        risk_subject = []
        dbg = {}
        if isinstance(result, dict):
            risk_subject = result.get("risk_subject", [])
            if debug_flag:
                dbg = result.get("debug", {})

        found = bool(risk_subject)
        llm_resp = "" if found else "抱歉，无法检索到相关答案"
        exec_time = int((time.time() - t0) * 1000)

        data = {
            "llmRespond": llm_resp,
            "lawRisk": "",
            "questionExtend": rec_questions,
            "conversationId": "",
            "messageId": "",
            "roundNumber": 0,
            "conversationInfo": {},
            "knowledgeSources": [],
            "totalKnowledgeSources": 0,
            "executionTime": exec_time,
            "workflowStatus": "ok" if found else "no_match",
            "executionSteps": [],
            "costStatistics": {},
            "workflowTrackingId": "",
            "risk_subject": risk_subject,
            "debug": dbg if debug_flag else {},
        }
        resp = {"success": True, "message": "OK", "data": data}
        return jsonify(resp)
    except Exception as e:
        print(f"lawrisk_search error: {e}")
        return jsonify({"success": False, "message": str(e), "data": {}}), 500


def _extract_params():
    """Extract parameters from request."""
    if request.method == "GET":
        query = request.args.get("query") or request.args.get("q") or request.args.get("text")
        debug_flag = request.args.get("debug") in {"1", "true", "yes", "on"}
        top_k = request.args.get("top")
        try:
            top_k_int = int(top_k) if top_k else 5
        except Exception:
            top_k_int = 5
        mode_value = (request.args.get("mode") or "llm").lower()
        region_value = request.args.get("region") or request.args.get("region_id")
        region_list = request.args.getlist("region")
        if region_list and (not region_value or len(region_list) > 1):
            region_value = region_list
    else:
        if request.is_json:
            payload = request.get_json(silent=True) or {}
        else:
            payload = request.form.to_dict(flat=True) if request.form else {}

        query = payload.get("query") or payload.get("q") or payload.get("text")
        debug_flag = str(payload.get("debug", "")).strip().lower() in {"1", "true", "yes", "on"}
        try:
            top_k_int = int(payload.get("top", 5))
        except Exception:
            top_k_int = 5
        mode_value = str(payload.get("mode", "llm")).lower()
        region_value = payload.get("region") or payload.get("region_id")

    return query, debug_flag, top_k_int, mode_value, region_value
