import threading
import uuid
from .store import CHAT_JOBS, CHAT_LOCK
from oci_genai_llm_graphrag_rerank_rfp import answer_question


def start_chat_job(question: str):

    job_id = str(uuid.uuid4())

    with CHAT_LOCK:
        CHAT_JOBS[job_id] = {
            "status": "PROCESSING",
            "result": None,
            "error": None,
            "logs": []
        }

    def log(msg):
        with CHAT_LOCK:
            CHAT_JOBS[job_id]["logs"].append(str(msg))

    def background():
        try:
            log("Starting answer_question()")

            result = answer_question(question)

            with CHAT_LOCK:
                CHAT_JOBS[job_id]["result"] = result
                CHAT_JOBS[job_id]["status"] = "DONE"

            log("DONE")

        except Exception as e:
            with CHAT_LOCK:
                CHAT_JOBS[job_id]["error"] = str(e)
                CHAT_JOBS[job_id]["status"] = "ERROR"

            log(f"ERROR: {e}")

    threading.Thread(target=background, daemon=True).start()

    return job_id