from datetime import datetime

from sqlalchemy.orm import Session

from app.models.chat_history import ChatHistory
from app.models.user_session import UserSession
from app.services.kb_service import KBService


class ChatbotService:
    def __init__(self) -> None:
        self.kb = KBService()

    def _upsert_session(
        self,
        db: Session,
        session_id: str,
        user_name: str,
        employee_id: str | None = None,
        department: str | None = None,
        device_name: str | None = None,
    ) -> None:
        session = db.query(UserSession).filter(UserSession.session_id == session_id).first()

        if not session:
            session = UserSession(
                session_id=session_id,
                user_name=user_name,
                employee_id=employee_id,
                department=department,
                device_name=device_name,
                started_at=datetime.utcnow(),
                last_activity_at=datetime.utcnow(),
            )
            db.add(session)
        else:
            session.user_name = user_name
            session.employee_id = employee_id
            session.department = department
            session.device_name = device_name
            session.last_activity_at = datetime.utcnow()

        db.commit()

    def get_categories(self) -> list[dict]:
        return [
            {"code": category["code"], "title": category["title"]}
            for category in self.kb.get_categories()
        ]

    def get_sub_options(self, category_code: str) -> list[dict]:
        return [
            {"code": item["code"], "title": item["title"]}
            for item in self.kb.get_sub_options(category_code)
        ]

    def get_answer(self, db: Session, session_id: str, user_name: str, category_code: str, sub_code: str) -> dict:
        item = self.kb.get_sub_option(category_code, sub_code)
        if not item:
            return {"reply": "Issue details not found.", "steps": [], "chat_id": 0}

        reply = item["title"]
        steps = item.get("steps", [])

        chat = ChatHistory(
            session_id=session_id,
            user_name=user_name,
            employee_id=None,
            department=None,
            device_name=None,
            user_message=item["title"],
            bot_reply=reply + "\n\n" + "\n".join(steps),
            issue_code=sub_code,
            issue_title=item["title"],
            detected_category=category_code.title(),
            resolution_status="Pending",
        )
        db.add(chat)
        db.commit()
        db.refresh(chat)

        return {
            "chat_id": chat.id,
            "reply": reply,
            "steps": steps,
        }

    def process(
        self,
        db: Session,
        session_id: str,
        user_name: str,
        message: str,
        employee_id: str | None = None,
        department: str | None = None,
        device_name: str | None = None,
    ) -> dict:
        self._upsert_session(db, session_id, user_name, employee_id, department, device_name)

        chat = ChatHistory(
            session_id=session_id,
            user_name=user_name,
            employee_id=employee_id,
            department=department,
            device_name=device_name,
            user_message=message,
            bot_reply=f"Message received: {message}",
            issue_code=None,
            issue_title=None,
            detected_category="General",
            resolution_status="Pending",
        )
        db.add(chat)
        db.commit()
        db.refresh(chat)

        return {
            "chat_id": chat.id,
            "reply": f"Message received: {message}",
            "steps": [],
            "issue_code": None,
            "issue_title": None,
            "detected_category": "General",
            "quick_actions": [],
        }