import uuid
from flask import Blueprint, render_template, request, jsonify
from flask_login import current_user
from app.extensions import db, csrf
from app.models.features import ChatMessage

chatbot_bp = Blueprint("chatbot", __name__, url_prefix="/chatbot")


@chatbot_bp.route("/api/message", methods=["POST"])
@csrf.exempt
def message():
    data = request.get_json(silent=True) or {}
    user_msg = data.get("message", "").strip()
    session_id = data.get("session_id", uuid.uuid4().hex)

    if not user_msg:
        return jsonify({"error": "Empty message"}), 400

    ChatMessage(session_id=session_id, role="user", content=user_msg)

    features_context = """You are the Jadwa AI assistant on the landing page. Help visitors understand the platform.
Key features: AI Feasibility Studies (SWOT, PESTEL, Porter's, VRIO, TAM/SAM/SOM, BMC, Lean Canvas),
Financial Analysis with Interactive Charts, PDF/PPTX/Gamma.app Export, AI Video Generation (Google Veo/Sora),
Social Publishing (6 platforms), WhatsApp Campaigns, Competitor Intelligence, Company Registration (Saudi WATHQ),
Business Incubator Applications, AI Business Advisor, Brand Kit Generator, Multi-Currency Support (10 currencies).
Plans: Free (2 reports/month), Pro ($29/mo, 50 reports), Enterprise ($99/mo, unlimited).
Answer in the same language as the user. Be concise and helpful. Guide them to sign up."""

    try:
        from app.ai.diamond import call_ai, run_sync
        messages = [
            {"role": "system", "content": features_context},
            {"role": "user", "content": user_msg},
        ]
        reply = run_sync(call_ai(messages, model_type="fast"))
    except Exception:
        reply = "مرحباً! أنا مساعد Jadwa AI. يمكنني مساعدتك في فهم المنصة. للبدء، سجل حساب مجاني وأنشئ أول دراسة جدوى."

    cm_user = ChatMessage(session_id=session_id, role="user", content=user_msg)
    cm_bot = ChatMessage(session_id=session_id, role="assistant", content=reply)
    db.session.add(cm_user)
    db.session.add(cm_bot)
    db.session.commit()

    return jsonify({"reply": reply, "session_id": session_id})
