import json
import logging
import os
import time
import asyncio

import socket
from datetime import datetime
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
from services.hr_graph import hr_graph
from services.cache_service import get_cached_query, set_cached_query
from services.nlp_service import fast_classify
from services.log_service import store_hr_log
import services.quota_service as quota_service
from routers.admin_quota import router as admin_quota_router

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

from services.redis_chat_service import add_user_message, add_ai_message, get_messages, _get_redis
import services.erp_client as erp_client

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

logger = logging.getLogger(__name__)

# Intents that must always run live, never be served from the generic
# query-text cache (keyed on company_id + normalized query text — NOT on
# the individual user):
#   - apply_leave/leave_balance/leave_status carry real side effects (Redis
#     slot state, an erp-api submission). Replaying a cache hit for these
#     would skip setting the slot state entirely — a second conversation
#     asking the exact same phrase would get a response implying slots were
#     captured (e.g. "full day or half day?") when none actually were,
#     breaking the very next turn.
#   - punch_details returns one EMPLOYEE'S OWN attendance record for a
#     specific day. Since the cache key has no per-user component, caching
#     it would let a cache hit from one employee's query serve THEIR punch
#     data to any other employee in the same company who happens to phrase
#     a punch question the same way — a privacy leak, not just staleness
#     (also stale outright for relative dates like "today"/"yesterday" once
#     more than a day has passed since the entry was cached).
#   - attendance_explain, for a related reason: its answer is tied to a
#     specific calendar day and the underlying attendance record can change
#     (e.g. after a regularization) — caching by query text alone would
#     silently replay a stale explanation for what looks like the same
#     question.
#   - leave_eligibility is here for a different reason than the others: it has no
#     slot state, but its answer depends on the caller's confirmation status and
#     on live erp-api policy config, either of which can change. Replaying a
#     cached "not eligible" for up to REDIS_EXPIRATION would keep telling a
#     newly-confirmed employee they don't qualify.
#   - cancel_leave is also mid-flow stateful (selection, then confirmation) —
#     serving a cached reply would answer the wrong turn of someone else's
#     conversation.
_STATEFUL_QUERY_INTENTS = {
    "apply_leave",
    "leave_balance",
    "leave_status",
    "punch_details",
    "attendance_explain",
    "leave_eligibility",
    "cancel_leave",
    # A "which leave do you mean?" disambiguation reply (see
    # leave_action_service.py) — depends on the caller's live pending/
    # approved leave list exactly like cancel_leave itself; must never be
    # served from cache for the same reason.
    "cancel_ask",
}

# 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.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 _check_redis() -> dict:
    client = _get_redis()
    if not client:
        return {"status": "degraded", "latency_ms": None, "error_code": "REDIS_UNAVAILABLE"}
    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_UNAVAILABLE"}


@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,
    }
    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=20, 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", **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)),
        )


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) -> None:
    """Populate query cache, write the HR log, and persist token usage.
    DB + Redis persistence already happened before 'done' was yielded."""
    answer_text = full_result.get("data", {}).get("answer", "") if full_result else ""
    detected_intent = full_result.get("intent") or detected_intent
    result_to_save = {
        "success": status == "success",
        "intent": full_result.get("intent") or detected_intent,
        "data": full_result.get("data") if full_result else None,
    }
    if (is_fresh_query and full_result and full_result.get("is_hr", True) and answer_text
            and detected_intent not in _STATEFUL_QUERY_INTENTS):
        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=full_result.get("intent") or detected_intent, response=result_to_save,
        source="ai", total_time=round(time.time() - start_time, 2),
        ai_time=round(ai_time, 2), status=status, **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)


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",
        )

    await _record_ai_msg(company_id, conversation_id, 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,
                     quota_warnings: list | None = None,
                     title_usage: dict | None = None,
                     bearer_token: str | None = None):
    """Core LangGraph streaming generator for /hr-assist-stream."""
    ai_start = time.time()
    full_result = None
    detected_intent = "general"
    status = "failure"

    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)

    initial_state = {
        "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,
    }

    try:
        async for event in hr_graph.astream(initial_state, stream_mode="custom"):
            etype = event.get("type")
            if etype == "intent":
                detected_intent = event.get("intent", "general")
                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.")
                    msg_payload = {"success": False, "intent": "blocked", "data": {"answer": guardrail_msg}}
                    await run_in_threadpool(save_message, db, conversation_id, company_id, query, msg_payload)
                    status = "blocked"
                    full_result = {"data": {"answer": guardrail_msg}, "is_hr": False}
                    yield _sse({"type": "done", "conversation_id": conversation_id,
                                "intent": "blocked", "cached": False,
                                "blocked": True, "server_ip": server_ip})
            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"):
                yield _sse(event)
            elif etype == "done":
                full_result = event
                status = "success"
                done_payload = await _persist_and_build_done(
                    event, query, conversation_id,
                    company_id, detected_intent, db, server_ip,
                )
                yield _sse(done_payload)
            elif etype == "error":
                yield _sse(event)
                yield _sse({"type": "done", "conversation_id": conversation_id,
                            "intent": detected_intent, "cached": False,
                            "blocked": True, "server_ip": server_ip})
    except Exception as e:
        logger.exception("Stream error: %s", e)
        yield _sse({"type": "error", "message": str(e)})
        yield _sse({"type": "done", "conversation_id": conversation_id,
                    "intent": detected_intent, "cached": False,
                    "blocked": True, "server_ip": server_ip})
    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,
        )


# ── 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")

    # 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")
    user_meta = {
        "user_type": user_payload.get("user_type"),
        "company_id": company_id,
        "company_name": user_payload.get("company_name"),
        "role_id": role_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)
    logger.info("STREAM | history_turns=%d", len(context_messages))
    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")
    return StreamingResponse(
        _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,
                   quota_warnings=quota.get("warnings"), title_usage=title_usage,
                   bearer_token=bearer_token),
        media_type="text/event-stream",
    )


@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))