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


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):
            return str((resp.get("data") or {}).get("answer") or 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_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
