import threading
import json
from pathlib import Path

from .store import ARCH_JOBS, ARCH_LOCK
from oci_genai_llm_graphrag_rerank_rfp import call_architecture_planner, architecture_to_mermaid

ARCH_FOLDER = Path("architecture")
ARCH_FOLDER.mkdir(exist_ok=True)

def make_job_logger(job_id: str):
    def _log(msg):
        with ARCH_LOCK:
            job = ARCH_JOBS.get(job_id)
            if job:
                job["logs"].append(str(msg))
    return _log

def start_architecture_job(job_id: str, question: str):
    job_dir = ARCH_FOLDER / job_id
    job_dir.mkdir(parents=True, exist_ok=True)

    status_file = job_dir / "status.json"
    result_file = job_dir / "architecture.json"

    def write_status(state: str, detail: str | None = None):
        payload = {"status": state}
        if detail:
            payload["detail"] = detail
        status_file.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")

        with ARCH_LOCK:
            if job_id in ARCH_JOBS:
                ARCH_JOBS[job_id]["status"] = state
                if detail:
                    ARCH_JOBS[job_id]["detail"] = detail

    write_status("PROCESSING")

    def background():
        try:
            logger = make_job_logger(job_id)

            plan = call_architecture_planner(question, log=logger)
            if not isinstance(plan, dict):
                raise TypeError(f"Planner returned {type(plan)}")

            plan["mermaid"] = architecture_to_mermaid(plan)

            result_file.write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding="utf-8")
            write_status("DONE")

        except Exception as e:
            write_status("ERROR", str(e))

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