import os
import re
import uuid
import logging
import json
import sys
import random
import pprint

from flask import Flask, request, jsonify, render_template
from sqlalchemy.sql import func

from openai import OpenAI
from rag_service import generate_rag_addendum
from db import SessionLocal, init_db
from utils.prompt_manager import build_messages_payload
from models import (
    Session as ChatSession, User, Case, Message, Document, Topic
)

print("📍 being here 1", flush=True)

# --- DIRECT KEY USAGE (no .env dependency required) ---
FALLBACK_OPENAI_KEY = "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"  # <-- your temp key
def _resolve_api_key():
    # If you still export OPENAI_API_KEY in the environment, we'll prefer it.
    # Otherwise we fall back to the hardcoded testing key above.
    k = (os.getenv("OPENAI_API_KEY") or FALLBACK_OPENAI_KEY or "").strip()
    if not k:
        raise RuntimeError("No API key available (OPENAI_API_KEY and FALLBACK_OPENAI_KEY are empty).")
    return k

_client = None
def get_openai_client() -> OpenAI:
    global _client
    if _client is None:
        api_key = _resolve_api_key()
        logging.getLogger().info("🔑 OPENAI_API_KEY ends with: ...%s", api_key[-4:])
        _client = OpenAI(api_key=api_key)
    return _client

print(f"🗄 DB user: {os.getenv('DB_USER')}")
for var in ("HTTP_PROXY","HTTPS_PROXY","ALL_PROXY"):
    if os.getenv(var):
        logging.getLogger().warning("Proxy var %s is set; may cause 401s: %s", var, os.getenv(var))

app = Flask(__name__)
init_db()

# @app.route("/")
# def hello():
#    return "✅ Dynbot backend is running."

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/init-session", methods=["POST"])
def init_session():
    db = SessionLocal()
    data = request.get_json()

    tenant_id = data.get("tenant_id", 1)
    user_id = data.get("user_id", 1)
    session_token = data.get("session_token", str(uuid.uuid4()))

    # Ensure user exists
    user = db.query(User).filter_by(id=user_id).first()
    if not user:
        user = User(id=user_id, tenant_id=tenant_id, username="Default User", email="default@example.com")
        db.add(user)
        db.commit()

    # Always create a new session
    new_session = ChatSession(
        tenant_id=tenant_id,
        user_id=user_id,
        session_token=session_token,
    )
    db.add(new_session)
    db.commit()
    db.refresh(new_session)

    # Create a case before closing the session
    case = Case(
        tenant_id=tenant_id,
        user_id=user_id,
        session_id=new_session.id
    )
    db.add(case)
    db.commit()
    db.refresh(case)

    # ✅ Access attributes before db.close()
    response = {
        "session_id": new_session.id,
        "session_token": session_token,
        "case_id": case.id
    }

    db.close()
    return jsonify(response)


@app.route("/cases", methods=["POST"])
def create_case():
    db = SessionLocal()
    tenant_id = request.json.get("tenant_id", 1)
    new = Case(tenant_id=tenant_id, title=request.json.get("title",""))
    db.add(new); db.commit(); db.refresh(new)
    db.close()
    return jsonify({"case_id": new.id}), 201

@app.route("/cases/<int:case_id>/history", methods=["GET"])
def get_history(case_id):
    db = SessionLocal()
    msgs = db.query(Message).filter_by(case_id=case_id).order_by(Message.timestamp).all()
    # If you later add FollowupQuestion to models, import it and use it here.
    db.close()
    return jsonify({
        "messages": [{"role":m.role,"content":m.content,"timestamp":m.timestamp.isoformat()} for m in msgs]
    })

@app.route("/cases/<int:case_id>/messages", methods=["POST"])
def post_message(case_id):
    db = SessionLocal()
    try:
        data = request.get_json() or {}
        user_text = data.get("content")
        button_choice = data.get("button_choice", "")
        tenant_id = data.get("tenant_id", 1)

        if not user_text or not tenant_id:
            return jsonify({"error": "bad_request", "detail": "Missing 'content' or 'tenant_id'"}), 400

        # 1) Store user message
        user_msg = Message(case_id=case_id, role="user", content=user_text, button_choice=button_choice)
        db.add(user_msg); db.commit(); db.refresh(user_msg)

        # 2) Build prompt payload
        messages_payload = build_messages_payload(db, case_id, tenant_id)

        # 3) Call OpenAI
        openai_client = get_openai_client()  # ✅ correct variable name
        try:
            resp = openai_client.chat.completions.create(
                model="gpt-4o-mini",
                messages=messages_payload,
                tools=[{
                    "type": "function",
                    "function": {
                        "name": "extract_followups",
                        "description": "Suggest 2–4 follow-up questions based on the assistant's reply.",
                        "parameters": {
                            "type": "object",
                            "properties": {"questions": {"type": "array", "items": {"type": "string"}}},
                            "required": ["questions"]
                        }
                    }
                }],
                tool_choice="auto"
            )
        except Exception as e:
            return jsonify({"error": "openai_call_failed", "detail": str(e)}), 502

        # 3b) Unpack choice/message robustly
        choice = resp.choices[0]
        msg = getattr(choice, "message", None)
        finish = getattr(choice, "finish_reason", None)

        if finish == "tool_calls" and msg and getattr(msg, "tool_calls", None):
            tool_call = msg.tool_calls[0]
            args = json.loads(getattr(tool_call.function, "arguments", "{}") or "{}")
            followups = args.get("questions", [])
            ai_text = msg.content or "Vielen Dank für Ihre Auswahl. Hier sind mögliche nächste Schritte oder Zusammenfassungen."
        else:
            followups = []
            ai_text = (msg.content if msg else "") or "(no text reply provided)"

        # 4) Truncate numbered list to max 3 items (keep intro before the first number)
        if ai_text:
            lines = ai_text.split("\n")
            first_idx = next((i for i, line in enumerate(lines) if re.match(r"^\d+\.\s", line)), None)
            if first_idx is not None:
                numbered = [ln for ln in lines if re.match(r"^\d+\.\s", ln)]
                truncated = numbered[:3]
                ai_text = "\n".join(lines[:first_idx] + truncated)

        # 5) Extract bold headings as choices (max 3; random if >3)
        choices = re.findall(r"\*\*(.*?)\*\*", ai_text)
        if len(choices) > 3:
            choices = random.sample(choices, 3)

        # 5.1) RAG addendum (optional)
        rag_addendum = ""
        try:
            rag_res = generate_rag_addendum(user_text, tenant_id=tenant_id, top_k=3)
            rag_addendum = (rag_res.get("addendum") or "").strip()
        except Exception:
            rag_addendum = ""

        if rag_addendum:
            ai_text += (
                "\n\n---\n\n"
                '<div class="rag-box">'
                "📘 <strong>Empfehlung aus den House of PM Best Practices</strong><br>"
                f"{rag_addendum}"
                "</div>"
            )

        # 6) Store assistant reply
        ai_msg = Message(case_id=case_id, role="assistant", content=ai_text)
        db.add(ai_msg); db.commit(); db.refresh(ai_msg)

        # Determine summary turn
        past_messages = db.query(Message).filter_by(case_id=case_id).order_by(Message.timestamp).all()
        turn = len([m for m in past_messages if m.role == "user"])
        is_summary = (turn == 3)

        if is_summary:
            intro_doc = db.query(Document).filter_by(tenant_id=tenant_id, title="summary_intro_1").first()
            quotes = db.query(Document).filter_by(tenant_id=tenant_id, title="quote").all()

            intro_text = intro_doc.content if intro_doc else ""
            quote_text = random.choice(quotes).content if quotes else ""

            button_choices = [m.button_choice for m in past_messages if m.role == "user"]
            intro_filled = (intro_text or "").format(
                iteration1=(button_choices[0] if len(button_choices) > 0 else ""),
                iteration2=(button_choices[1] if len(button_choices) > 1 else ""),
                iteration3=(button_choices[2] if len(button_choices) > 2 else "")
            )

            ai_text = f"{intro_filled}\n\n{ai_text}\n\n {quote_text}"

            if rag_addendum:
                ai_text += "\n\n---\n\n"

        return jsonify({
            "reply": ai_text,
            "followups": followups,              # frontend currently ignores, still returned
            "choices": ([] if is_summary else choices),
            "is_summary": is_summary
        })

    except Exception as e:
        return jsonify({"error": "server_error", "detail": str(e)}), 500
    finally:
        db.close()

@app.route("/tenants", methods=["POST"])
def create_tenant():
    db = SessionLocal()
    name = request.json["name"]
    t = models.Tenant(name=name)
    db.add(t); db.commit(); db.refresh(t)
    db.close()
    return jsonify({"tenant_id": t.id}), 201


@app.route("/topics/random", methods=["GET"])
def get_random_topics():
    db = SessionLocal()
    tenant_id = 1  # or dynamic if implemented
    raw_topics = db.query(Topic)\
        .filter_by(tenant_id=tenant_id)\
        .order_by(func.random())\
        .limit(3)\
        .all()

    # Replace {topic} in question field
    results = []
    for t in raw_topics:
        filled_question = t.question.replace("{topic}", t.topic)
        results.append({
            "topic": t.topic,
            "question": filled_question
        })

    db.close()
    return jsonify(results)    


if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port=5002,
        ssl_context=(
            '/var/www/html/decompression/certs/fullchain.pem',
            '/var/www/html/decompression/certs/privkey.pem'
        ),
        debug=True
    )

