from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from models.conversation_model import Conversation
from models.message_model import Message
import json


def create_conversation(db: Session, company_id: int, title: str, original_query: str = None):
    convo = Conversation(company_id=company_id, title=title, original_query=original_query)
    db.add(convo)
    db.commit()
    db.refresh(convo)
    return convo


def save_message(db: Session, conversation_id: str, company_id: int, query: str, response):
    if isinstance(response, dict):
        response = json.dumps(response)
    msg = Message(
        conversation_id=conversation_id,
        company_id=company_id,
        content=query,
        ai_response=response,
    )
    db.add(msg)
    db.commit()
    return msg


def mark_awaiting_confirmation_canceled(db: Session, conversation_id: str, company_id: int, intent: str) -> None:
    """Flips is_conceled to True on EVERY stored message in this conversation
    carrying the given awaiting-confirmation intent (e.g. "regularization_
    awaiting_confirmation"), so once the user confirms or cancels, a
    reloaded conversation shows all of that flow's past pending cards as
    resolved instead of re-offering their confirm/cancel actions. Must be
    called before the current (confirm/cancel) turn's own row is saved, so
    that row itself — which doesn't carry this intent — is never matched."""
    rows = (
        db.query(Message)
        .filter(Message.conversation_id == conversation_id, Message.company_id == company_id)
        .all()
    )
    changed = False
    for msg in rows:
        if not msg.ai_response:
            continue
        try:
            resp = json.loads(msg.ai_response) if isinstance(msg.ai_response, str) else msg.ai_response
            if isinstance(resp, str):
                resp = json.loads(resp)
        except Exception:
            continue
        if not isinstance(resp, dict) or resp.get("intent") != intent:
            continue
        data = resp.get("data")
        if not isinstance(data, dict):
            continue
        data["is_conceled"] = True
        msg.ai_response = json.dumps(resp)
        changed = True
    if changed:
        db.commit()


#: Card fields that say nothing about what the employee saw.
_CARD_KEYS_NOT_FOR_HISTORY = {"answer", "options", "is_conceled", "access_notice", "suggestions"}
_CARD_HISTORY_MAX_CHARS = 1500


def history_text(data) -> str:
    """The assistant turn as the model's history should hold it: the answer
    text plus the data of the card it came with.

    UAT (26 Oct) UV-02: a card turn reached history as its one-line caption
    ("Here's your current leave balance."), so "Interesting, why is that?",
    "Why is it showing Not Recorded?" and "Which one is the oldest?" had no
    figures, days or requests to talk about, and were answered "I do not
    have this information" / "Could you clarify what you're referring to?".
    Capped, so a long list does not crowd out the conversation."""
    if not isinstance(data, dict):
        return ""
    answer = str(data.get("answer") or "")
    card = {k: v for k, v in data.items()
            if k not in _CARD_KEYS_NOT_FOR_HISTORY and v not in (None, "", [], {})}
    if not card:
        return answer
    try:
        dumped = json.dumps(card, default=str, ensure_ascii=False)
    except Exception:
        return answer
    if len(dumped) > _CARD_HISTORY_MAX_CHARS:
        dumped = dumped[:_CARD_HISTORY_MAX_CHARS] + "...(truncated)"
    return f"{answer}\n(Card data shown with this answer: {dumped})".strip()


def _parse_ai_response(raw) -> str:
    """Extract answer text from a stored ai_response value (str or dict)."""
    if not raw:
        return ""
    try:
        resp = json.loads(raw) if isinstance(raw, str) else raw
        if isinstance(resp, str):
            resp = json.loads(resp)
        if isinstance(resp, dict):
            data = resp.get("data") or {}
            return history_text(data) or str(resp.get("result", ""))
    except Exception:
        pass
    return ""


def get_context(db: Session, conversation_id: str, company_id: int, limit: int = 10):
    rows = (
        db.query(Message)
        .filter(Message.conversation_id == conversation_id, Message.company_id == company_id)
        .order_by(Message.created_at.desc())
        .limit(limit)
        .all()
    )
    result = []
    for msg in reversed(rows):
        result.append({"role": "user", "content": msg.content or ""})
        answer = _parse_ai_response(msg.ai_response)
        if answer:
            result.append({"role": "assistant", "content": answer})
    return result


def _parse_ai_response_full(raw) -> dict | None:
    """Unlike _parse_ai_response (text-only, for LLM context), this keeps the
    full stored payload — intent + the structured 'data' object (leave type/
    dates/session/total days for a confirmation card, leave_quota for a
    balance card, the leaves list for a status card, etc.) that save_message
    persisted verbatim from the stream's 'done' event. Used for reloading a
    past conversation in the UI, where the modal/card needs that structured
    data, not just its flattened answer text."""
    if not raw:
        return None
    try:
        resp = json.loads(raw) if isinstance(raw, str) else raw
        if isinstance(resp, str):
            resp = json.loads(resp)
        if isinstance(resp, dict):
            return {"intent": resp.get("intent"), "data": resp.get("data") or {}}
    except Exception:
        pass
    return None


def get_last_intent(db: Session, conversation_id: str, company_id: int) -> str | None:
    """The intent of the most recent turn in this conversation that recorded
    one, or None for a fresh conversation (or one whose stored payloads
    carry no intent).

    Needed because nothing else carries an intent ACROSS turns: the graph
    builds a fresh state per query, and redis_chat_service stores only
    role + content. Without this, a bare follow-up fragment that names
    only a date ("4th Wednesday of August 2026" right after a punch-details
    answer) has no way to be recognized as a continuation of the intent it
    is refining — see hr_graph.classify_node's follow-up override, which
    used to label exactly that case "follow_up" and route it to the
    generic HR answer node, answering the date as trivia instead of
    looking up that day's punches.

    Scans backwards rather than reading only the single latest row: a turn
    can be stored with intent None (a guardrail block, an error), and the
    conversation's actual topic is the last one that named an intent."""
    rows = (
        db.query(Message)
        .filter(Message.conversation_id == conversation_id, Message.company_id == company_id)
        .order_by(Message.created_at.desc())
        .limit(10)
        .all()
    )
    for msg in rows:
        parsed = _parse_ai_response_full(msg.ai_response)
        if parsed and parsed.get("intent"):
            return parsed["intent"]
    return None


def get_full_history(db: Session, conversation_id: str, company_id: int, limit: int = 50):
    """Like get_context, but for displaying a reopened conversation in the
    UI rather than feeding an LLM prompt — each assistant turn keeps its
    intent + full structured data so the frontend can re-render the same
    leave balance/confirmation/status card it showed live, instead of a
    bare text bubble."""
    rows = (
        db.query(Message)
        .filter(Message.conversation_id == conversation_id, Message.company_id == company_id)
        .order_by(Message.created_at.desc())
        .limit(limit)
        .all()
    )
    result = []
    for msg in reversed(rows):
        created_at = msg.created_at.isoformat() if msg.created_at else None
        result.append({"role": "user", "content": msg.content or "", "created_at": created_at})
        parsed = _parse_ai_response_full(msg.ai_response)
        if parsed:
            result.append({
                "role": "assistant",
                "content": parsed["data"].get("answer", ""),
                "intent": parsed.get("intent"),
                "data": parsed["data"],
                "created_at": created_at,
            })
    return result


def get_conversations(db: Session, company_id: int):
    return (
        db.query(Conversation)
        .filter(Conversation.company_id == company_id, Conversation.is_deleted == 0)
        .order_by(Conversation.updated_at.desc())
        .all()
    )


def get_conversation_by_id(db, conversation_id, company_id):
    return db.query(Conversation).filter(
        Conversation.id == conversation_id,
        Conversation.company_id == company_id,
        Conversation.is_deleted == 0,
    ).first()


def create_conversation_with_id(db, conversation_id, company_id, title, original_query: str = None):
    """Adopts a client-supplied conversation_id as the row's primary key.

    Returns the created Conversation, or None on a primary-key collision —
    that id string is already in use (by this company or, per the caller's
    prior company-scoped lookup, more likely another one). Callers must
    treat None as "mint a fresh server-generated id instead", NEVER as
    permission to look up/adopt/reuse the existing row under that id — see
    main.py's _resolve_conversation, which is the only caller and depends on
    this contract to avoid ever exposing another company's conversation."""
    convo = Conversation(id=conversation_id, company_id=company_id, title=title, original_query=original_query)
    db.add(convo)
    try:
        db.commit()
    except IntegrityError:
        db.rollback()
        return None
    db.refresh(convo)
    return convo


def update_conversation_title(db: Session, conversation_id: str, company_id: int, title: str) -> None:
    convo = db.query(Conversation).filter(
        Conversation.id == conversation_id,
        Conversation.company_id == company_id,
    ).first()
    if convo:
        convo.title = title
        db.commit()


def delete_conversation_from_db(db, conversation_id, company_id):
    convo = db.query(Conversation).filter(
        Conversation.id == conversation_id,
        Conversation.company_id == company_id,
        Conversation.is_deleted == 0,
    ).first()
    if not convo:
        return False
    convo.is_deleted = 1
    db.commit()
    return True
