from __future__ import annotations

from sqlalchemy.orm import Session

from app.models.knowledge import HumanAttentionHistory, HumanAttentionRecord

URGENT_TERMS = ("自杀", "不想活", "自伤", "伤害别人", "杀人", "现实危险")
IMPORTANT_TERMS = ("绝望", "撑不住", "崩溃", "非常痛苦", "反复失败", "没有办法")
CONTACT_TERMS = ("联系老师", "找老师", "人工帮助", "人工客服")


class HumanAttentionService:
    @staticmethod
    def create_if_needed(
        db: Session,
        *,
        session_id: int,
        message_id: int,
        user_id: int,
        question: str,
        answer: str,
        knowledge_missing: bool,
    ) -> HumanAttentionRecord | None:
        priority = None
        reason = None
        if any(term in question for term in URGENT_TERMS):
            priority, reason = "urgent", "检测到现实危险或自伤伤人风险"
        elif any(term in question for term in IMPORTANT_TERMS):
            priority, reason = "important", "用户表达持续或强烈痛苦"
        elif any(term in question for term in CONTACT_TERMS):
            priority, reason = "normal", "用户主动要求联系老师或人工"
        elif knowledge_missing:
            priority, reason = "normal", "课程或业务问题缺少可靠正式知识"
        if priority is None:
            return None
        record = HumanAttentionRecord(
            session_id=session_id,
            message_id=message_id,
            user_id=user_id,
            trigger_message=question,
            problem_summary=_summary(question),
            trigger_reason=reason,
            priority=priority,
            status="pending",
        )
        db.add(record)
        db.flush()
        db.add(
            HumanAttentionHistory(
                attention_id=record.id,
                from_status=None,
                to_status="pending",
                note=f"系统自动创建；回答摘要：{_summary(answer, 200)}",
                operated_by=0,
            )
        )
        return record


def _summary(text: str, limit: int = 120) -> str:
    value = " ".join(text.split())
    return value if len(value) <= limit else value[:limit].rstrip() + "…"
