import json
import logging
import os
import time
import asyncio

import socket
from datetime import datetime, timedelta
from typing import Annotated
from fastapi import FastAPI, Depends, Body, Header, HTTPException
from fastapi.responses import StreamingResponse
from sqlalchemy import text
from sqlalchemy.orm import Session
from fastapi.middleware.cors import CORSMiddleware
from fastapi.concurrency import run_in_threadpool

from database import get_db, init_db, SessionLocal
from models.server_ip_log import ServerIPLog
from dependencies import verify_jwt_token, enforce_token_quota, extract_role, is_manager_role
from services.hr_graph import hr_graph, conversation_category, GENERAL_CHAT_INTENT
from services import graph_checkpointer, flow_interrupts, redis_health
from schema.agent import HRState
from services.cache_service import get_cached_query, set_cached_query
from services.nlp_service import fast_classify, mentions_summary
from services.log_service import store_hr_log, count_recent_turns
import services.quota_service as quota_service
from routers.admin_quota import router as admin_quota_router
from routers.admin_cache import router as admin_cache_router
from routers.admin_feature_flags import router as admin_feature_flags_router
import services.feature_flag_service as feature_flag_service
from recruitment.router import router as recruitment_router
from routers.voice import router as voice_router


from services.chat_service import (
    create_conversation,
    get_conversation_by_id,
    save_message,
    get_context,
    history_text,
    get_full_history,
    get_last_intent,
    get_conversations,
    create_conversation_with_id,
    delete_conversation_from_db,
    mark_awaiting_confirmation_canceled,
)
from services.ai_service import LLM_TASK_MAX_TOKENS
from services.ai_service import (_call_llm, _extract_text, _normalize_usage, _check_moderation,
                                 INTENT_MODEL, ACTIVE_LLM_PROVIDER, ACTIVE_CHAT_MODEL)

from redis.exceptions import AuthenticationError, AuthenticationWrongNumberOfArgsError
from services.redis_chat_service import (
    add_user_message,
    add_ai_message,
    get_messages,
    _get_redis,
    last_connection_error,
)
import services.erp_client as erp_client
import services.chat_inflight as chat_inflight

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(message)s"
)

logger = logging.getLogger(__name__)

#: Exchanges (one question + its answer each) loaded for a summary of the chat
#: - see the summary branch where history is loaded.
_SUMMARY_HISTORY_EXCHANGES = 20

_STATEFUL_QUERY_INTENTS = {
    "apply_leave",
    "leave_balance",
    "leave_status",
    "punch_details",
    "attendance",
    "HRMS_TEAM_ATTENDANCE_QUERY",
    "attendance_explain",
    "leave_eligibility",
    "cancel_leave",
    
    "cancel_ask",
    "leave_type_clarify",
    # Bare-verb clarification ("apply" with no object). Same reason as
    # leave_type_clarify directly above: classify_node's bare-verb fast-path
    # WRITES bare_verb_clarify_state before answering, so a replayed cache hit
    # would show the "What would you like to apply for?" card while recording
    # nothing for the reply to resolve against — the next turn would then be
    # classified with no memory that a question was outstanding.
    "clarify_needed",
    # Policy DRAFTING, both turns. The first WRITES policy_draft_state
    # before asking what the policy should cover, so a replayed cache hit
    # would show the question while recording nothing for the answer to
    # resolve against — the reply would then be classified as a fresh
    # question and answered from the policy documents. The second turn is
    # a document generated for one specific brief; replaying it for
    # anyone who happens to type the same words would hand them someone
    # else's draft.
    "policy_draft",
    "policy_draft_clarify",
    "HRMS_TEAM_LEAVE_QUERY",
    # The roster and "is X on my team?". Missing here, the answer was cached
    # and a repeat of the question was replayed as TEXT ONLY - no team card -
    # from a roster read earlier. QA: the same question answered differently,
    # and without its card, on the second send.
    "HRMS_TEAM_MEMBERS_QUERY",
    # Read from the caller's own leave requests - per user, and it changes.
    "reporting_manager",
    "reporting_manager_contact",
    # The holiday calendar is the caller's DEPARTMENT's, but the cache key is
    # per company: cached, one department's list (or its "not available for
    # your department") was replayed to every other department.
    "leave_holidays",
    # Model-written replies to "..." and to another employee's pay (UV-12):
    # cached, the same words were replayed every time.
    "other_employee_pay",
    "apply_for_someone_else",
    "shift_query",
    "manager_leave_request_lookup",
    "manager_attendance_explanation",
    "manager_leave_approval",
    # Attendance regularization, both sides. These were missing, and all
    # three are live-record flows a cache must never answer:
    #   regularisation                  - the employee's own SUBMIT flow; a
    #                                     replayed confirmation would claim a
    #                                     request was filed that never was.
    #   manager_regularisation_view     - a queue that changes every time a
    #                                     request is approved, so a manager
    #                                     could act on a stale list.
    #   manager_regularisation_approval - state-changing by definition.
    # Observed live: a view that failed mid-restart was cached and then
    # replayed as an empty answer on every later ask.
    "regularisation",
    "manager_regularisation_view",
    "manager_regularisation_approval",
    "large_team_review",
    "bulk_approvals",
    "shift_planning",
    "comparative_reporting",
    # HA-193 - the manager-only refusals. Two reasons a cache must never
    # answer these, and the first is what was actually reported:
    #
    #   * The refusal is a CARD, not prose. Its "Not available" payload
    #     rides on the `access_notice` event and inside `done`'s `data`
    #     (services/access_notice.py), and the query cache stores only the
    #     answer TEXT - so a replay through _serve_cache_hit re-emits the
    #     two sentences as a bare `chunk` with no payload anywhere, and the
    #     amber card silently degrades to an ordinary chat bubble. Because
    #     the cache is only read on the first turn of a conversation, the
    #     card rendered in the conversation that produced it and then
    #     stopped rendering in the next ones - "sometimes it comes and
    #     sometimes it doesn't".
    #   * A refusal is a permission decision with erp-api as the authority,
    #     and REDIS_EXPIRATION outlives a role change: promote someone to
    #     manager and they keep being told no for the rest of the hour.
    "team_leave_restricted",
    "team_attendance_restricted",
    "team_members_restricted",
    "attendance_restricted",
    # P1 (Oct 26) - conversation. A reply to "no way" or "hi" is written for
    # that moment, not looked up. Cached, the first one written froze for the
    # whole company: the pre-fix "Got it! How can I assist you with HR or
    # workforce-related matters today?" was replayed, word for word, to every
    # fresh "no way" for up to REDIS_EXPIRATION (30 days in .env.example),
    # long after the prompt that wrote it was fixed.
    "greeting",
    "small_talk",
}

# Intents that resolve a regularization request one way or another — once
# any of these is reached, every earlier "regularization_awaiting_
# confirmation" card in the conversation is stale and gets is_conceled=True.
_REGULARIZATION_RESOLVING_INTENTS = {
    "regularization_cancelled",
    "regularization_submitted",
    "regularization_partial",
}

app = FastAPI()

_env = os.getenv("ENV", "development")

_cors_env_map = {
    "production": "CORS_ORIGINS_PRODUCTION",
    "staging":    "CORS_ORIGINS_STAGING",
}
_cors_env_key = _cors_env_map.get(_env, "CORS_ORIGINS_LOCAL")
_cors_raw = os.getenv(_cors_env_key, "")
_cors_origins = [o.strip() for o in _cors_raw.split(",") if o.strip()]

logger.info("CORS env=%s  origins=%s", _env, _cors_origins)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

init_db()

app.include_router(admin_quota_router)
app.include_router(admin_cache_router)
app.include_router(admin_feature_flags_router)
app.include_router(recruitment_router)
app.include_router(voice_router)

# Remove voice temp workspaces a SIGKILL'd worker left behind. Without this,
# recorded audio (PII) accumulates on disk indefinitely across unclean
# restarts; the per-request `finally` only covers the normal path.
# Module-level like init_db() above, rather than an @app.on_event("startup")
# handler, which is deprecated in this FastAPI version.
try:
    import services.audio_intake as _audio_intake
    _audio_intake.sweep_stale()
except Exception as _e:  # never block startup on cleanup
    logger.warning("Voice temp sweep skipped: %s", _e)


# Keep the ASR model resident. Measured on the live gateway: the first
# transcription after an idle period takes ~35s while warm calls take ~1s —
# so without this the cold start lands on whoever opens the app first, and
# looks to them like a hang rather than a slow reply.
#
# Deliberately fire-and-forget: a keep-warm task must never delay startup or
# take the app down, and if it fails the only consequence is the behaviour we
# have today.
@app.on_event("startup")
async def _voice_warmup() -> None:
    try:
        import services.transcribe_client as _tc
        asyncio.create_task(_tc.warmup_loop())
    except Exception as _e:
        logger.warning("Voice warmup not scheduled: %s", _e)



@app.get("/")
async def root():
    return {"status": "ok", "service": "helixtaai", "docs": "/docs"}


_cached_server_ip: str | None = None


def _resolve_ip_native() -> str:
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.connect(("8.8.8.8", 80))
        return s.getsockname()[0]


def _store_server_ip(ip: str) -> None:
    db = SessionLocal()
    try:
        db.add(ServerIPLog(
            ip_address=ip,
            hostname=socket.gethostname(),
            environment=os.getenv("ENV", "development"),
        ))
        db.commit()
    except Exception as e:
        logger.warning(f"Failed to store server IP log: {e}")
    finally:
        db.close()


async def _get_server_ip() -> str:
    global _cached_server_ip
    if _cached_server_ip:
        return _cached_server_ip
    try:
        ip = await run_in_threadpool(_resolve_ip_native)
        _cached_server_ip = ip
        await run_in_threadpool(_store_server_ip, ip)
    except Exception:
        _cached_server_ip = "unavailable"
    return _cached_server_ip


@app.get("/server-info")
async def server_info(_: Annotated[dict, Depends(verify_jwt_token)]):
    """Returns the server's outbound public IP — the IP that hits OpenAI/DeepSeek APIs."""
    ip = await _get_server_ip()
    return {
        "outbound_ip": ip,
        "note": "Add this IP to your OpenAI / DeepSeek whitelist"
    }


# ── /ping: cross-service health check ──────────────────────────────────────────
# Postgres/Redis failures are advisory only (flip "status" to "degraded", never
# the HTTP status code) — only the erp-api leg controls the status code, since
# that's what proves the JWT-scoped cross-service channel actually works.

def _check_postgres(db: Session) -> dict:
    start = time.monotonic()
    try:
        db.execute(text("SELECT 1"))
        return {"status": "ok", "latency_ms": round((time.monotonic() - start) * 1000, 1)}
    except Exception as e:
        logger.warning("Postgres health check failed: %s", e)
        return {"status": "degraded", "latency_ms": None, "error_code": "POSTGRES_UNAVAILABLE"}


def _redis_error_code(exc) -> str:
    """Auth failures get their own code: production Redis requires a password, so
    a missing or wrong REDIS_PASSWORD is the likeliest cause and it otherwise
    looks identical to an unreachable server."""
    if isinstance(exc, (AuthenticationError, AuthenticationWrongNumberOfArgsError)):
        return "REDIS_AUTH_FAILED"
    return "REDIS_UNAVAILABLE"


def _check_redis() -> dict:
    client = _get_redis()
    if not client:
        return {
            "status": "degraded",
            "latency_ms": None,
            "error_code": _redis_error_code(last_connection_error()),
        }
    start = time.monotonic()
    try:
        client.ping()
        return {"status": "ok", "latency_ms": round((time.monotonic() - start) * 1000, 1)}
    except Exception as e:
        logger.warning("Redis health check failed: %s", e)
        return {"status": "degraded", "latency_ms": None, "error_code": _redis_error_code(e)}


def _check_state_stores() -> dict:
    try:
        return redis_health.check_state_stores()
    except Exception as e:
        logger.warning("Redis state-store check failed: %s", e)
        return {"status": "error", "error": type(e).__name__, "stores": {}}


@app.get("/ping")
async def ping(
    authorization: str = Header(...),
    db: Session = Depends(get_db),
    user_payload: Annotated[dict, Depends(verify_jwt_token)] = None,
):
    """Proves the JWT-scoped helixta-api → erp-api channel works end-to-end,
    forwarding the caller's own token — never a stored service credential."""
    bearer_token = authorization.split(None, 1)[1]
    timestamp = datetime.utcnow().isoformat() + "Z"

    postgres_status = await run_in_threadpool(_check_postgres, db)
    redis_status = await run_in_threadpool(_check_redis)

    status_code = 200
    try:
        logger.info("erp-api ping with caller token %s", bearer_token[:10] + "...")
        result = await erp_client.ping(bearer_token, company_id=user_payload.get("user_id"))
        logger.info("erp-api ping result: %s", result)
        erp_status = {
            "status": "ok",
            "http_status": result["http_status"],
            "latency_ms": result["latency_ms"],
            "error_code": None,
        }
    except erp_client.ErpApiTimeout:
        erp_status = {"status": "error", "http_status": None, "latency_ms": None, "error_code": "ERP_API_TIMEOUT"}
        status_code = 504
    except (erp_client.ErpApiUnavailable, erp_client.ErpApiUnauthorized):
        erp_status = {"status": "error", "http_status": None, "latency_ms": None, "error_code": "ERP_API_UNAVAILABLE"}
        status_code = 503

    dependencies = {"postgres": postgres_status, "redis": redis_status, "erp_api": erp_status}
    body = {
        "status": "ok" if all(d["status"] == "ok" for d in dependencies.values()) else "degraded",
        "timestamp": timestamp,
        "dependencies": dependencies,
        # Advisory, outside "status": every conversation-state store as THIS
        # worker sees it (settings + connection, no secrets). The "redis" entry
        # above checks the chat client only; a store that cannot connect makes
        # its flow forget itself between messages while chat history looks fine.
        "redis_state_stores": await run_in_threadpool(_check_state_stores),
    }
    if status_code != 200:
        raise HTTPException(status_code=status_code, detail=body)
    return body


# ── Streaming endpoint helpers ────────────────────────────────────────────────

def _sse(payload: dict) -> str:
    return f"data: {json.dumps(payload)}\n\n"


async def _build_title(query: str) -> tuple[str, dict | None]:
    """
    Generate a 3-5 word ChatGPT-style title from the user query using a
    small fast model. Falls back to a truncated query on any error.
    Returns (title, usage) — usage is None if the call failed/skipped.
    """
    try:
        prompt = (
            "Generate a concise conversation title (3-5 words, title case, "
            "no quotes, no punctuation at the end) for a chat that starts with:\n\n"
            f"{query[:300]}"
        )
        raw = await asyncio.wait_for(
            _call_llm(prompt, max_tokens=LLM_TASK_MAX_TOKENS, model=INTENT_MODEL), timeout=4.0
        )
        title = _extract_text(raw).strip().strip('"\'').strip()
        usage = _normalize_usage(raw.get("usage")) if isinstance(raw, dict) else None
        return (title[:60] if title else ""), usage
    except Exception as e:
        logger.warning("Title build failed: %s", e)
        return "", None


def _fallback_title(query: str, max_len: int = 60) -> str:
    """Word-boundary truncation used when LLM title generation fails."""
    q = query.strip()
    if len(q) <= max_len:
        return q
    return q[:max_len].rsplit(" ", 1)[0] + "…"


async def _resolve_conversation(db, conversation_id, company_id: int, query: str) -> tuple[str, dict | None]:
    """
    Returns (conversation_id, title_usage). For NEW conversations, generates a
    smart title from the query synchronously before creating the row — title
    is correct in DB from the very first request, no background task needed.

    If conversation_id is supplied and already resolves to a row owned by
    this company_id, it's reused as-is. Otherwise it's ADOPTED — the row is
    created using that exact id — which is what lets a client generate its
    own conversation_id up front and have it persist across an entire
    multi-turn conversation (this app's Angular client does exactly that; it
    never omits conversation_id, even for a brand-new chat — regression fix:
    the previous version of this function never adopted an unowned id, which
    silently reset conversation state, including in-progress apply-leave
    slots, on EVERY turn).

    The only case that refuses to adopt is an actual primary-key collision —
    create_conversation_with_id returns None when that exact id string
    already exists. Since this company's own ids were already caught by the
    lookup above, a collision here can only mean the id belongs to a
    different company; a fresh server-generated id is minted instead. This
    still never adopts or exposes another company's existing conversation,
    and never behaves differently based on WHY an id wasn't already owned by
    this company (never-seen vs. someone else's) — both a genuinely fresh id
    and someone else's id look identical up front (get_conversation_by_id
    returns None either way); the collision is only discovered, and only
    matters, at the INSERT itself.
    """
    title, title_usage = await _build_title(query)
    title = title or _fallback_title(query)
    if conversation_id:
        convo = await run_in_threadpool(get_conversation_by_id, db, conversation_id, company_id)
        if convo:
            return conversation_id, title_usage
        adopted = await run_in_threadpool(
            create_conversation_with_id, db, conversation_id, company_id, title, query
        )
        if adopted:
            return conversation_id, title_usage
        logger.warning(
            "Conversation id %s already taken (belongs to another company) — minting a fresh id instead",
            conversation_id,
        )
    convo = await run_in_threadpool(create_conversation, db, company_id, title, query)
    return convo.id, title_usage


async def _load_chat_history(company_id: int, conversation_id: str, db) -> list:
    """Redis → DB fallback. Always returns previous turns only (current query not included)."""
    try:
        messages = await asyncio.wait_for(
            run_in_threadpool(get_messages, company_id, conversation_id), timeout=1
        )
    except Exception as e:
        logger.warning("Redis history read failed: %s", e)
        messages = []
    if not messages:
        messages = await run_in_threadpool(get_context, db, conversation_id, company_id, 20)
    return messages


async def _record_user_msg(company_id: int, conversation_id: str, query: str) -> None:
    try:
        await asyncio.wait_for(
            run_in_threadpool(add_user_message, company_id, conversation_id, query), timeout=1
        )
    except Exception as e:
        logger.warning("Redis user write failed: %s", e)


async def _record_ai_msg(company_id: int, conversation_id: str, answer: str) -> None:
    if not answer:
        return
    try:
        await asyncio.wait_for(
            run_in_threadpool(add_ai_message, company_id, conversation_id, answer), timeout=2
        )
    except Exception as e:
        logger.warning("Redis AI write failed: %s", e)


async def _serve_cache_hit(db, cached: dict, query: str, conversation_id: str,
                           company_id: int, user_meta: dict, start_time: float,
                           quota_warnings: list | None = None):
    """Persist the cached exchange to history then stream it to the client.
    No LLM call is made here, so no token usage is recorded."""
    answer = cached.get("result", "")
    intent = cached.get("intent")

    await run_in_threadpool(
        save_message, db, conversation_id, company_id, query,
        {"success": True, "intent": intent, "data": {"answer": answer}},
    )
    await _record_ai_msg(company_id, conversation_id, answer)

    await run_in_threadpool(
        store_hr_log,
        db=db, query=query, intent=intent, response=answer, source="cache",
        total_time=round(time.time() - start_time, 2), ai_time=0,
        status="success" if answer else "failure",
        # No graph state on a cache hit, so the category comes from the intent
        # alone. is_hr is implied True: a non-HR turn is never cached.
        category=conversation_category(intent or "", is_hr=True),
        conversation_id=conversation_id,
        # No model was called, so provider/model stay empty rather than
        # claiming a call that did not happen.
        **user_meta,
    )

    async def _stream():
        content = answer if isinstance(answer, str) else json.dumps(answer)
        yield _sse({"type": "quota_status", "warnings": quota_warnings or []})
        yield _sse({"type": "guardrail", "stage": "input", "status": "skipped", "message": "Served from cache"})
        yield _sse({"type": "intent", "intent": intent, "conversation_id": conversation_id})
        yield _sse({"type": "chunk", "content": content})
        yield _sse({"type": "done", "conversation_id": conversation_id, "intent": intent, "cached": True})

    return StreamingResponse(_stream(), media_type="text/event-stream")


def _record_usage_events(db, usage_events: list, *, user_id: int, true_company_id,
                         role_id, conversation_id: str) -> None:
    for ev in usage_events:
        usage = ev.get("usage") or {}
        total_tokens = usage.get("total_tokens")
        if not total_tokens:
            continue
        quota_service.record_usage(
            db,
            user_id=user_id,
            company_id=true_company_id,
            role_id=role_id,
            conversation_id=conversation_id,
            provider=ACTIVE_LLM_PROVIDER,
            model=None,
            source=ev.get("source", "unknown"),
            prompt_tokens=usage.get("prompt_tokens"),
            completion_tokens=usage.get("completion_tokens"),
            total_tokens=total_tokens,
            is_estimated=bool(ev.get("is_estimated", False)),
        )


# Output moderation runs after the answer has streamed, so it cannot stop one
# going out; it keeps a flagged answer out of the cache and raises it in the
# logs for review. Off unless OUTPUT_MODERATION_ENABLED is on; the judge is
# MODERATION_PROVIDER's (see ai_service.moderation_provider).
_output_moderation_tasks: set = set()


def _output_moderation_enabled() -> bool:
    return os.getenv("OUTPUT_MODERATION_ENABLED", "false").strip().lower() in ("1", "true", "yes", "on")


async def _output_is_flagged(answer_text: str, query: str, conversation_id) -> bool:
    if not (answer_text and _output_moderation_enabled()):
        return False
    try:
        result = await _check_moderation(answer_text[:4000])
    except Exception as e:
        logger.warning("Output moderation failed (allowing): %s", e)
        return False
    if result.get("flagged"):
        logger.error("[Guardrail:Output] FLAGGED | categories=%s | conversation=%s | query=%s",
                     result.get("categories"), conversation_id, (query or "")[:80])
        return True
    return False


async def _finalize_ai_stream(full_result, detected_intent: str, status: str,
                              is_fresh_query: bool, query: str,
                              user_meta: dict, db,
                              start_time: float, ai_time: float,
                              conversation_id: str, company_id: int, true_company_id, role_id,
                              extra_usage_events: list | None = None,
                              routed: tuple | None = None,
                              failure_stage: str | None = None) -> None:
    """Populate query cache, write the HR log, and persist token usage.
    DB + Redis persistence already happened before 'done' was yielded.

    `routed` is the (intent, is_hr) the graph announced before answering. It
    decides the analytics category whenever the turn did not end in a normal
    reply: a blocked input or a crashed turn is carried with is_hr=False (to
    keep it out of the cache), and categorising from that counted every one
    of them as GENERAL chat. With no announced intent at all (blocked before
    classification) the category is left empty rather than guessed."""
    # A general-chat non-answer still came from a real done event, so it is
    # categorised from that, like a success.
    if status == "success" or str(failure_stage or "").startswith("general_chat"):
        category = conversation_category(
            ((full_result or {}).get("intent") or detected_intent or ""),
            is_hr=bool(full_result.get("is_hr", True)) if full_result else True)
    elif routed:
        category = conversation_category(routed[0] or "", is_hr=bool(routed[1]))
    else:
        category = None
    # full_result is None whenever the stream ended WITHOUT a `done` event:
    # an exception caught by the handler above, or - the common one - the
    # client disconnecting mid-stream, since CancelledError is not an
    # Exception and unwinds straight past that handler into the `finally`
    # that calls this.
    #
    # Every read here was written to tolerate that, but three of them were
    # missing the guard and raised AttributeError from inside the `finally`.
    # A raise there REPLACES whatever was already unwinding, so the real
    # stream error was logged and then buried under a traceback about
    # NoneType - the symptom that was actually reaching the ASGI layer.
    answer_text = full_result.get("data", {}).get("answer", "") if full_result else ""
    if full_result:
        detected_intent = full_result.get("intent") or detected_intent
    result_to_save = {
        "success": status == "success",
        "intent": detected_intent,
        "data": full_result.get("data") if full_result else None,
    }
    cacheable = (is_fresh_query and full_result and full_result.get("is_hr", True) and answer_text
                 and detected_intent not in _STATEFUL_QUERY_INTENTS)
    if cacheable:
        # Checked first: a flagged answer must never be served again from cache.
        cacheable = not await _output_is_flagged(answer_text, query, conversation_id)
    elif answer_text and _output_moderation_enabled():
        task = asyncio.create_task(_output_is_flagged(answer_text, query, conversation_id))
        _output_moderation_tasks.add(task)
        task.add_done_callback(_output_moderation_tasks.discard)
    if cacheable:
        try:
            await run_in_threadpool(set_cached_query, query, company_id,
                                    {"success": True, "intent": detected_intent, "result": answer_text})
        except Exception as e:
            logger.warning("Cache write failed: %s", e)
    await run_in_threadpool(
        store_hr_log,
        db=db, query=query, intent=detected_intent, response=result_to_save,
        source="ai", total_time=round(time.time() - start_time, 2),
        ai_time=round(ai_time, 2), status=status,
        category=category,
        conversation_id=conversation_id,
        failure_stage=failure_stage,
        provider=ACTIVE_LLM_PROVIDER,
        model=ACTIVE_CHAT_MODEL,
        **user_meta,
    )

    usage_events = list(full_result.get("usage_events", [])) if full_result else []
    if extra_usage_events:
        usage_events.extend(extra_usage_events)
    if usage_events:
        await run_in_threadpool(
            _record_usage_events, db, usage_events,
            user_id=user_meta["company_id"], true_company_id=true_company_id,
            role_id=role_id, conversation_id=conversation_id,
        )

    logger.info("STREAM DONE | status=%s | ai_time=%.2fs", status, ai_time)


#: What the user sees whenever a turn cannot be answered: the LLM classifier
#: unreachable, a node raising, a node emitting "error". It goes out as an
#: ordinary reply (chunk + done, blocked=False) and never as an "error" SSE
#: event - the client turns an "error" event (or blocked=True) into its own
#: "something went wrong. please try again", and there must always be a
#: real answer in the bubble instead.
#: Says the turn failed (28 Oct): the old greeting ("Hi, I'm Helix AI! ...
#: What can I help you with today?") read as if the question had never
#: arrived. Same text as hr_graph.NODE_FAILURE_MESSAGE.
_STREAM_FAILURE_MESSAGE = (
    "Sorry, I couldn't finish that just now - please try again in a moment. "
    "I'm Helix AI and can help with your leave, attendance, regularization and shifts."
)
_STREAM_FAILURE_INTENT = "general"

#: How a general-chat turn that produced no real answer is logged (FR-09
#: "successful vs failed responses"). The stage names are hr_graph's.
_STATUS_BY_FAILURE_STAGE = {
    "general_chat_llm": "failure",
    "general_chat_rate_limited": "rate_limited",
}


def _checkpoint_run_kwargs(company_id, conversation_id) -> dict:
    """With the checkpointer on: the conversation's checkpoint thread, saved
    once when the run ends or pauses ("exit") - not after every step, which
    would cost a few database round trips per node. Off: nothing, and the
    graph is called exactly as before. Decided by the compiled graph itself,
    not the env var: it was compiled at import, and a checkpointer with no
    thread_id is an error."""
    if getattr(hr_graph, "checkpointer", None) is None:
        return {}
    return {"config": graph_checkpointer.thread_config(company_id, conversation_id),
            "durability": "exit"}


def _general_chat_hourly_limit() -> int:
    """GENERAL_CHAT_HOURLY_LIMIT: general answers per user per rolling hour
    (FR-08). 0 or less means unlimited. Read per request, so changing it needs
    no restart."""
    try:
        return int(os.getenv("GENERAL_CHAT_HOURLY_LIMIT", "30"))
    except ValueError:
        return 30


def _fallback_events(conversation_id: str, server_ip: str) -> list[dict]:
    """The chunk + done pair that closes a turn with the Helix fallback reply."""
    answer_data = {"answer": _STREAM_FAILURE_MESSAGE}
    return [
        {"type": "chunk", "content": _STREAM_FAILURE_MESSAGE},
        {"type": "done", "conversation_id": conversation_id,
         "intent": _STREAM_FAILURE_INTENT, "cached": False,
         "blocked": False, "server_ip": server_ip,
         "message": _STREAM_FAILURE_MESSAGE, "data": answer_data},
    ]


async def _save_fallback_turn(db, conversation_id: str, company_id: int, query: str) -> None:
    """Persist the fallback reply so history shows the same bubble. Best
    effort: a DB/Redis failure here must not stop the reply going out."""
    try:
        await _record_ai_msg(company_id, conversation_id, _STREAM_FAILURE_MESSAGE)
        await run_in_threadpool(
            save_message, db, conversation_id, company_id, query,
            {"success": False, "intent": _STREAM_FAILURE_INTENT,
             "data": {"answer": _STREAM_FAILURE_MESSAGE}},
        )
    except Exception as e:
        logger.warning("Saving fallback reply failed: %s", e)


async def _persist_and_build_done(
    event: dict, query: str,
    conversation_id: str, company_id: int,
    detected_intent: str, db, server_ip: str,
) -> dict:
    """Persist exchange to Redis + DB and return the done SSE payload."""
    answer_text = event.get("data", {}).get("answer", "")
    intent = event.get("intent") or detected_intent
    msg_payload = {"success": True, "intent": intent, "data": event.get("data")}

    if intent in _REGULARIZATION_RESOLVING_INTENTS:
        # The user just confirmed or cancelled the regularization request —
        # every earlier "regularization_awaiting_confirmation" card in this
        # conversation is now resolved. Flip is_conceled on all of them
        # before saving this turn, so this turn's own row (which doesn't
        # carry that intent) is never matched by the update.
        await run_in_threadpool(
            mark_awaiting_confirmation_canceled, db, conversation_id, company_id,
            "regularization_awaiting_confirmation",
        )

    # The card's data goes into history with its caption (UAT UV-02).
    await _record_ai_msg(company_id, conversation_id,
                         history_text(event.get("data") or {}) or answer_text)
    await run_in_threadpool(save_message, db, conversation_id, company_id, query, msg_payload)

    return {**event, "conversation_id": conversation_id, "cached": False, "server_ip": server_ip}


async def _ai_stream(query: str, context_messages: list, conversation_id: str,
                     company_id: int, is_fresh_query: bool, user_meta: dict,
                     db, start_time: float, server_ip: str,
                     true_company_id=None, role_id=None,
                     last_intent: str | None = None,
                     quota_warnings: list | None = None,
                     title_usage: dict | None = None,
                     bearer_token: str | None = None,
                     is_manager_jwt: bool = False):
    """Core LangGraph streaming generator for /hr-assist-stream."""
    ai_start = time.time()
    full_result = None
    detected_intent = "general"
    status = "failure"
    # Exactly one closing "done" per turn, whichever path produces it.
    done_sent = False

    yield _sse({"type": "quota_status", "warnings": quota_warnings or []})

    nlp_intent, _, nlp_confidence = fast_classify(query)
    pre_intent = nlp_intent if (nlp_intent and nlp_confidence >= 0.5) else "general"
    logger.info("STREAM | nlp_intent=%s confidence=%.2f injected=%s", nlp_intent, nlp_confidence, pre_intent)

    # Resolved HERE, once per request, because the graph has no DB session.
    # Two independent switches, both of which must be on: the feature_flags
    # row (what Product flips through POST /admin/feature-flags/general_chat,
    # no deploy) and the GENERAL_CHAT_MASTER_ENABLED env var (engineering's
    # kill-switch, which overrides the row). is_enabled() fails CLOSED on any
    # DB error, so a database the app cannot read turns the lane OFF rather
    # than on. Read per request, never cached: a cached kill-switch is not a
    # kill-switch.
    #
    # Threadpooled like every other sync DB call on this path — a blocking
    # query here would stall the event loop for every concurrent stream.
    #
    # Product decision: non-HR questions are ALWAYS answered by non_hr_node
    # (LLM + web search), never by general_chat_node, whatever the feature_flags
    # row or GENERAL_CHAT_MASTER_ENABLED say. To bring the general lane back,
    # restore the feature_flag_service.is_enabled(...) call here.
    general_chat_enabled = False
    # FR-08: a per-user allowance of general answers per rolling hour, so the
    # in-house model cannot be flooded through this lane. Counted only when
    # the lane is on; HR turns are never counted or limited by it.
    general_chat_over_limit = False
    general_limit = _general_chat_hourly_limit()
    if general_chat_enabled and general_limit > 0:
        used = await run_in_threadpool(
            count_recent_turns, db, company_id, GENERAL_CHAT_INTENT,
            datetime.utcnow() - timedelta(hours=1),
        )
        general_chat_over_limit = used >= general_limit

    initial_state = {
        # Every key of the state, every turn - None unless set below. With the
        # checkpointer on (LANGGRAPH_CHECKPOINTER), a key this turn leaves out
        # would otherwise keep the LAST turn's value (its turn_instruction, its
        # error, its safety verdict...). Phase 5 carries state over on purpose,
        # by resuming a paused run - never through a key left unset here.
        # (The exception: a pausing flow's waiting card - flow_interrupts.PERSISTED_KEYS.)
        **{key: None for key in HRState.__annotations__ if key not in flow_interrupts.PERSISTED_KEYS},
        # Phase 5: the flows whose cards pause the run this turn.
        "interrupt_flows": flow_interrupts.enabled_flows(hr_graph),
        "query": query, "context": context_messages,
        "intent": pre_intent, "is_hr": True,
        "is_database_related": False, "has_date_expression": False,
        "moderation": {}, "output_guardrail": {},
        "response_text": "", "error": None, "usage_events": [],
        "bearer_token": bearer_token, "company_id": company_id,
        "conversation_id": conversation_id,
        "is_manager_jwt": is_manager_jwt,
        "last_intent": last_intent,
        # Resolved by hr_graph.manager_gate_node before classification runs;
        # seeded None so "not yet decided" is distinguishable from a real
        # False, and from MANAGER_UNKNOWN when erp-api can't be reached.
        "is_manager": None,
        # FR-01. _route_after_classify is the only reader; see
        # hr_graph._general_chat_may_take_the_turn.
        "general_chat_enabled": general_chat_enabled,
        "general_chat_over_limit": general_chat_over_limit,
    }
    # What the graph announced before answering (intent, is_hr), and the
    # stage a general-chat turn reports when it produced no real answer.
    # Both are for the analytics row only - see _finalize_ai_stream.
    routed = None
    failure_stage = None

    try:
        run_kwargs = _checkpoint_run_kwargs(company_id, conversation_id)
        run_input = initial_state
        if initial_state["interrupt_flows"]:
            # A reply to a paused card resumes that run; anything else starts
            # fresh (flow_interrupts.turn_input). Unreadable saved state: fresh.
            try:
                run_input = await flow_interrupts.turn_input(hr_graph, run_kwargs["config"], initial_state)
            except Exception:
                logger.exception("[Flow] could not read the saved state - a fresh run")
        async for event in hr_graph.astream(run_input, stream_mode="custom", **run_kwargs):
            etype = event.get("type")
            if etype == "intent":
                detected_intent = event.get("intent", "general")
                routed = (detected_intent, event.get("is_hr", True))
                yield _sse({**event, "conversation_id": conversation_id})
            elif etype == "guardrail":
                yield _sse(event)
                if event.get("status") == "failed":
                    guardrail_msg = event.get("message", "Your message was flagged by safety guardrails.")
                    # A permission refusal (the ownership guard's "someone
                    # else's attendance") brings its own card and intent: the
                    # "Access restricted" access_notice, and e.g.
                    # "attendance_restricted" instead of the generic "blocked".
                    # Both go into the saved message too, so history renders
                    # the same card. Safety/moderation refusals carry neither
                    # and are unchanged.
                    notice = event.get("access_notice")
                    blocked_intent = event.get("intent") or "blocked"
                    answer_data = {"answer": guardrail_msg}
                    if notice:
                        answer_data["access_notice"] = notice
                        yield _sse({"type": "access_notice", "data": notice})
                    msg_payload = {"success": False, "intent": blocked_intent, "data": answer_data}
                    await run_in_threadpool(save_message, db, conversation_id, company_id, query, msg_payload)
                    status = "blocked"
                    full_result = {"data": answer_data, "is_hr": False}
                    done_sent = True
                    # blocked=False on the wire: the refusal text IS the reply,
                    # and the client swaps blocked=True for its own "something
                    # went wrong". The intent still marks it as a refusal.
                    yield _sse({"type": "done", "conversation_id": conversation_id,
                                "intent": blocked_intent, "cached": False,
                                "blocked": False, "server_ip": server_ip,
                                "message": guardrail_msg, "data": answer_data})
            elif etype in ("searching", "chunk", "fetching_balance", "submitting_leave",
                           "fetching_status", "leave_balance", "leave_confirmation",
                           "leave_success", "leave_status", "fetching_attendance", "attendance_explanation",
                           "checking_eligibility", "leave_eligibility",
                           "leave_failure",
                           # Cancel-leave flow (leaves_kumargirinath). Emitted by
                           # leave_action_service but absent from this list on that
                           # branch, so every cancel card was being dropped here —
                           # the flow worked server-side and rendered nothing.
                           "cancelling_leave", "leave_cancel_success",
                           "leave_cancellation_preview", "leave_cancellation_selection",
                           "fetching_team_leaves", "team_pending_leave", "fetching_shift", "shift_summary",
                           "fetching_individual_report", "employee_selection",
                           "individual_leave_request", "individual_attendance_explanation",
                           "fetching_leave_approval", "leave_approval_confirmation",
                           "submitting_leave_approval", "leave_approval_success",
                           "fetching_team_attendance", "team_attendance_summary",
                           # Roster view. Absent from this list the events are
                           # dropped silently and the card never renders - the
                           # same way every cancel-leave card was lost.
                           "fetching_team_members", "team_members",
                           "navigation_card",
                           # HA-193 - the "Not available" permission card.
                           # Unlisted here it is dropped silently and the
                           # refusal renders as a plain bubble again.
                           "access_notice"):
                yield _sse(event)
            elif etype == "done":
                if done_sent:
                    continue
                # Internal only: never sent to the client or saved.
                event = dict(event)
                failure_stage = event.pop("failure_stage", None)
                full_result = event
                status = _STATUS_BY_FAILURE_STAGE.get(failure_stage, "failure") \
                    if failure_stage else "success"
                done_payload = await _persist_and_build_done(
                    event, query, conversation_id,
                    company_id, detected_intent, db, server_ip,
                )
                done_sent = True
                yield _sse(done_payload)
            elif etype == "error":
                # Never forwarded: the client renders an "error" event as its
                # own "something went wrong". The node's reason is logged and
                # the turn closes as a normal Helix reply instead.
                logger.warning("STREAM | node error replaced with fallback reply: %s",
                               event.get("message"))
                if done_sent:
                    continue
                status = "fallback"
                detected_intent = _STREAM_FAILURE_INTENT
                # is_hr False keeps the fallback out of the query cache.
                full_result = {"intent": _STREAM_FAILURE_INTENT, "is_hr": False,
                               "data": {"answer": _STREAM_FAILURE_MESSAGE},
                               "usage_events": []}
                await _save_fallback_turn(db, conversation_id, company_id, query)
                for ev in _fallback_events(conversation_id, server_ip):
                    yield _sse(ev)
                done_sent = True
        if not done_sent:
            # The graph finished without a reply of any kind - never leave
            # the client with an empty bubble.
            logger.warning("STREAM | graph ended without a done event - sending fallback reply")
            status = "fallback"
            detected_intent = _STREAM_FAILURE_INTENT
            await _save_fallback_turn(db, conversation_id, company_id, query)
            for ev in _fallback_events(conversation_id, server_ip):
                yield _sse(ev)
            done_sent = True
    except Exception as e:
        # Never str(e) to the user: it is an internal exception message. The
        # full error is in the log line below.
        logger.exception("Stream error: %s", e)
        if not done_sent:
            status = "fallback"
            detected_intent = _STREAM_FAILURE_INTENT
            await _save_fallback_turn(db, conversation_id, company_id, query)
            for ev in _fallback_events(conversation_id, server_ip):
                yield _sse(ev)
            done_sent = True
    finally:
        title_usage_event = [{"source": "title", "usage": title_usage}] if title_usage else None
        await _finalize_ai_stream(
            full_result, detected_intent, status, is_fresh_query,
            query, user_meta, db,
            start_time, time.time() - ai_start,
            conversation_id, company_id, true_company_id, role_id,
            extra_usage_events=title_usage_event,
            routed=routed,
            failure_stage=failure_stage or (
                "input_guardrail" if status == "blocked"
                else "graph" if status == "fallback" else None),
        )


# ── Route ─────────────────────────────────────────────────────────────────────

@app.post(
    "/hr-assist-stream",
    responses={400: {"description": "query field is required"}},
)
async def hr_assist_stream(
    request: dict = Body(...),
    authorization: str = Header(...),
    db: Session = Depends(get_db),
    user_payload: dict = Depends(verify_jwt_token),
    quota: dict = Depends(enforce_token_quota),
):
    start_time = time.time()
    query = request.get("query")
    if not query:
        raise HTTPException(status_code=400, detail="Query required")


    # ── One request at a time (AC8) ───────────────────────────────────────
    # The frontend already blocks a second send while isStreaming is true,
    # but that is a client-side promise. This is the server-side one.
    # Fails OPEN when Redis is down: the client guard still holds, and a
    # cache outage must not take chat down.
    # Scoped to the THREAD, not the person: a question in one chat must not
    # block another chat, and starting a fresh chat while an answer is still
    # streaming must simply work. Read from the request rather than from
    # _resolve_conversation below, because the lock has to be taken before any
    # work begins — and a brand-new chat has no id at this point by definition.
    _lock_user = user_payload.get("user_id")
    _lock_conv = request.get("conversation_id")
    if not await chat_inflight.acquire(_lock_user, _lock_conv):
        raise HTTPException(
            status_code=409,
            detail={"error_code": "request_in_progress",
                    "message": "Please wait for the current response to finish."},
        )
    # Ownership passes to the streaming generator once it is created; until
    # then this function's finally owns the release, so no exception path
    # between here and the return can wedge the user until the TTL expires.
    _stream_owns_lock = False
    try:
        # Forwarded to erp_client for leave_action_node's calls — same caller-owns-
        # their-own-token discipline as /ping, not a stored service credential.
        bearer_token = authorization.split(None, 1)[1]

        company_id = user_payload.get("user_id")
        true_company_id = user_payload.get("company_id")
        role_id = user_payload.get("role_id")

        # FR-07.3 — resolved once here, not inside the graph, so the manager-only
        # individual-report node never has to re-parse the token. False means
        # "the token didn't say", not "denied" — see dependencies.is_manager_role.
        jwt_role = extract_role(user_payload)
        is_manager_jwt = is_manager_role(user_payload)
        logger.info("STREAM | jwt_role=%s is_manager_jwt=%s", jwt_role, is_manager_jwt)
        user_meta = {
            "user_type": user_payload.get("user_type"),
            # NOTE: this is the USER id, despite the name — it is what the
            # hr_query_logs.company_id column has always held. The tenant is
            # true_company_id below. Both are logged: company_id counts active
            # Helix users, true_company_id groups usage by company (FR-09).
            "company_id": company_id,
            "company_name": user_payload.get("company_name"),
            "role_id": role_id,
            "true_company_id": true_company_id,
        }

        conversation_id, title_usage = await _resolve_conversation(
            db, request.get("conversation_id"), company_id, query
        )
        logger.info("STREAM | conv=%s company=%s", conversation_id, company_id)

        context_messages = await _load_chat_history(company_id, conversation_id, db)
        # A summary of this chat needs the chat, not its last 10 exchanges
        # (Redis keeps 20 messages). QA LF-01: 13-15 turn chats lost their
        # opening topics from the summary. The DB keeps every turn.
        if mentions_summary(query):
            summary_history = await run_in_threadpool(
                get_context, db, conversation_id, company_id, _SUMMARY_HISTORY_EXCHANGES)
            if len(summary_history) > len(context_messages):
                context_messages = summary_history
        logger.info("STREAM | history_turns=%d", len(context_messages))
        # The previous turn's intent, so classify_node can recognize a bare
        # follow-up fragment as a refinement of the topic already in progress
        # rather than an off-topic question (see its follow-up override).
        # Read from the DB because that is the only store that keeps an intent
        # per turn -- redis_chat_service holds role + content only.
        last_intent = await run_in_threadpool(get_last_intent, db, conversation_id, company_id)
        logger.info("STREAM | last_intent=%s", last_intent)
        await _record_user_msg(company_id, conversation_id, query)

        is_fresh_query = not context_messages
        if is_fresh_query:
            cached = None
            try:
                cached = await run_in_threadpool(get_cached_query, query, company_id)
            except Exception as e:
                logger.warning("Cache read failed: %s", e)
            if cached and cached.get("intent") in _STATEFUL_QUERY_INTENTS:
                logger.info("STREAM | Ignoring cache hit for stateful intent=%s — must run leave_action_node for real", cached.get("intent"))
                cached = None
            if cached:
                logger.info("STREAM | CACHE HIT")
                return await _serve_cache_hit(db, cached, query, conversation_id, company_id, user_meta,
                                              start_time, quota_warnings=quota.get("warnings"))

        server_ip = await _get_server_ip()
        logger.info("STREAM | AI START")
        # The lock must outlive this function: the response is only just
        # beginning when we return. Hand ownership to the generator, which
        # releases in its own finally — so the lock is held for exactly as long
        # as the turn is actually being produced, including when the client
        # disconnects mid-stream (that surfaces here as GeneratorExit).
        _stream_owns_lock = True
        return StreamingResponse(
            chat_inflight.release_after(
                _lock_user, _lock_conv,
                _ai_stream(query, context_messages, conversation_id, company_id,
                           is_fresh_query, user_meta, db, start_time, server_ip,
                           true_company_id=true_company_id, role_id=role_id,
                           last_intent=last_intent,
                           quota_warnings=quota.get("warnings"), title_usage=title_usage,
                           bearer_token=bearer_token, is_manager_jwt=is_manager_jwt),
            ),
            media_type="text/event-stream",
        )
    except HTTPException:
        raise
    except Exception as e:
        # Anything failing before the stream starts (DB, Redis, cache,
        # conversation lookup) used to surface as a 500, which the client
        # shows as "something went wrong". Answer with the Helix reply instead.
        logger.exception("STREAM | pre-stream failure, sending fallback reply: %s", e)
        fallback_conv = request.get("conversation_id") or ""

        async def _fallback_stream():
            yield _sse({"type": "quota_status", "warnings": quota.get("warnings") or []})
            for ev in _fallback_events(fallback_conv, _cached_server_ip or "unavailable"):
                yield _sse(ev)

        return StreamingResponse(_fallback_stream(), media_type="text/event-stream")
    finally:
        if not _stream_owns_lock:
            await chat_inflight.release(_lock_user, _lock_conv)


@app.post("/hr-assist-stop")
async def hr_assist_stop(
    request: dict = Body(default={}),
    user_payload: dict = Depends(verify_jwt_token),
):
    """Release this thread's in-flight slot immediately.

    Aborting the fetch already closes the SSE generator, whose `finally`
    releases the lock — so this is not the only path, and it is safe to call
    when nothing is held. It exists because that release is asynchronous and
    the user is not: pressing Stop and immediately resending raced the
    disconnect and came back 409, which reads as "the thing I just stopped is
    still running". Nothing else is torn down here; the generator's own finally
    still ends the turn.
    """
    await chat_inflight.release(user_payload.get("user_id"),
                                request.get("conversation_id"))
    return {"success": True}


@app.get("/my-usage")
async def my_usage(
    db: Session = Depends(get_db),
    user_payload: dict = Depends(verify_jwt_token),
):
    user_id = user_payload.get("user_id")
    role_id = user_payload.get("role_id")
    status = await run_in_threadpool(quota_service.usage_status, db, user_id, role_id)
    return {"success": True, **status}


@app.get("/conversations")
async def list_conversations(
    db: Session = Depends(get_db),
    user_payload: dict = Depends(verify_jwt_token)
):
    try:
        company_id = user_payload.get("user_id")

        if not company_id:
            raise HTTPException(status_code=401, detail="Unauthorized")

        logger.info(f"Listing conversations for Company={company_id}")

        data = await run_in_threadpool(get_conversations, db, company_id)

        return {
            "success": True,
            "count": len(data) if data else 0,
            "data": data
        }

    except Exception as e:
        logger.error(f"Error fetching conversations: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to fetch conversations")


@app.get("/conversations/{conversation_id}")
async def get_chat(
    conversation_id: str,
    db: Annotated[Session, Depends(get_db)],
    user_payload: Annotated[dict, Depends(verify_jwt_token)]
):
    try:
        company_id = user_payload.get("user_id")
        if not company_id:
            raise HTTPException(status_code=401, detail="Unauthorized")

        data = await run_in_threadpool(
            get_full_history, db, conversation_id, company_id, 50
        )

        if not data:
            raise HTTPException(status_code=404, detail="Conversation not found")

        return {
            "success": True,
            "conversation_id": conversation_id,
            "data": data
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    

@app.delete("/conversations/{conversation_id}")
async def delete_conversation(
    conversation_id: str,
    db: Annotated[Session, Depends(get_db)],
    user_payload: Annotated[dict, Depends(verify_jwt_token)]
):
    try:
        company_id = user_payload.get("user_id")
        if not company_id:
            raise HTTPException(status_code=401, detail="Unauthorized")

        deleted = await run_in_threadpool(delete_conversation_from_db, db, conversation_id, company_id)
        if not deleted:
            raise HTTPException(status_code=404, detail="Conversation not found")
        return {
            "success": True,
            "message": f"Conversation {conversation_id} deleted"
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))