"""
safety.py
----------
Crisis / imminent-danger detection. This module's job is ONLY to detect and
flag — it never attempts crisis counseling, diagnosis, or de-escalation
scripting beyond a short, empathetic redirect to real help. This mirrors the
"Emergency Safety" requirement: stop the normal screening flow, encourage
immediate real-world support, and do not pretend to be a crisis counselor.
"""

from dataclasses import dataclass
from typing import List, Optional

from . import lexicons
from .nlp_analysis import TextFeatures

SAFETY_MESSAGE = (
    "I want to pause here because what you're describing sounds really "
    "serious, and I care about your safety. I'm not able to provide crisis "
    "counseling, but you deserve support from someone who can help right now.\n\n"
    "If you are in immediate danger, please contact your local emergency "
    "number right away.\n\n"
    "You can also reach a crisis line for free, confidential support:\n"
    "  • US: call or text 988 (Suicide & Crisis Lifeline)\n"
    "  • UK & ROI: Samaritans, call 116 123\n"
    "  • Outside these regions: please search for a local crisis line, or "
    "contact a trusted person or licensed mental health professional near you.\n\n"
    "Please also consider telling someone you trust — a friend, family "
    "member, or doctor — what you just told me. This screening will pause "
    "for now; your wellbeing matters more than finishing it."
)


@dataclass
class SafetyCheckResult:
    triggered: bool
    reasons: List[str]
    matched_terms: List[str]

    @property
    def message(self) -> Optional[str]:
        return SAFETY_MESSAGE if self.triggered else None


class CrisisDetector:
    """Checks both free-text messages and questionnaire item 9 (PHQ-9) for
    signs of self-harm / suicidal ideation / immediate danger."""

    def check_text(self, features: TextFeatures) -> SafetyCheckResult:
        if features.crisis_markers:
            return SafetyCheckResult(
                triggered=True,
                reasons=["Crisis language detected in message text."],
                matched_terms=list(features.crisis_markers),
            )
        return SafetyCheckResult(triggered=False, reasons=[], matched_terms=[])

    def check_phq9_item9(self, item9_response: int) -> SafetyCheckResult:
        if item9_response and item9_response > 0:
            return SafetyCheckResult(
                triggered=True,
                reasons=[
                    "PHQ-9 item 9 (thoughts of self-harm or being better off "
                    "dead) endorsed above zero."
                ],
                matched_terms=[],
            )
        return SafetyCheckResult(triggered=False, reasons=[], matched_terms=[])

    def combine(self, *results: SafetyCheckResult) -> SafetyCheckResult:
        triggered = any(r.triggered for r in results)
        reasons = [r for res in results for r in res.reasons]
        terms = [t for res in results for t in res.matched_terms]
        return SafetyCheckResult(triggered=triggered, reasons=reasons, matched_terms=terms)
