"""
Addiction assessment models for substance use screening.
"""
from datetime import datetime
from enum import Enum
from typing import Dict, List, Optional, Tuple

from pydantic import Field, validator

from essencia.fields import EncryptedStr, EncryptedInt
from essencia.models.mental_health import (
    AssessmentType, 
    SeverityLevel, 
    AssessmentQuestion, 
    AssessmentResponse, 
    MentalHealthAssessment
)


class AUDITAssessment(MentalHealthAssessment):
    """Alcohol Use Disorders Identification Test (AUDIT) - WHO screening tool."""
    
    assessment_type: AssessmentType = Field(default=AssessmentType.AUDIT, frozen=True)
    
    # AUDIT-specific scoring
    hazardous_drinking_score: EncryptedInt  # Questions 1-3
    dependence_symptoms_score: EncryptedInt  # Questions 4-6
    harmful_alcohol_use_score: EncryptedInt  # Questions 7-10
    
    # Risk classification
    drinking_risk_level: str  # Low, Moderate, High, Very High
    intervention_recommendation: Optional[EncryptedStr] = None
    
    @classmethod
    def get_questions(cls) -> List[AssessmentQuestion]:
        """Get AUDIT questions."""
        questions = [
            # Hazardous alcohol use (Questions 1-3)
            AssessmentQuestion(
                question_id="audit_1",
                text="How often do you have a drink containing alcohol?",
                text_pt="Com que frequência você consome bebidas alcoólicas?",
                category="hazardous_drinking",
                options=[
                    {"value": 0, "label": "Never", "label_pt": "Nunca"},
                    {"value": 1, "label": "Monthly or less", "label_pt": "Mensalmente ou menos"},
                    {"value": 2, "label": "2-4 times a month", "label_pt": "2-4 vezes por mês"},
                    {"value": 3, "label": "2-3 times a week", "label_pt": "2-3 vezes por semana"},
                    {"value": 4, "label": "4 or more times a week", "label_pt": "4 ou mais vezes por semana"}
                ]
            ),
            AssessmentQuestion(
                question_id="audit_2",
                text="How many drinks containing alcohol do you have on a typical day when you are drinking?",
                text_pt="Quantas doses de álcool você consome tipicamente ao beber?",
                category="hazardous_drinking",
                options=[
                    {"value": 0, "label": "1 or 2", "label_pt": "1 ou 2"},
                    {"value": 1, "label": "3 or 4", "label_pt": "3 ou 4"},
                    {"value": 2, "label": "5 or 6", "label_pt": "5 ou 6"},
                    {"value": 3, "label": "7 to 9", "label_pt": "7 a 9"},
                    {"value": 4, "label": "10 or more", "label_pt": "10 ou mais"}
                ]
            ),
            AssessmentQuestion(
                question_id="audit_3",
                text="How often do you have six or more drinks on one occasion?",
                text_pt="Com que frequência você consome seis ou mais doses em uma única ocasião?",
                category="hazardous_drinking",
                options=[
                    {"value": 0, "label": "Never", "label_pt": "Nunca"},
                    {"value": 1, "label": "Less than monthly", "label_pt": "Menos que mensalmente"},
                    {"value": 2, "label": "Monthly", "label_pt": "Mensalmente"},
                    {"value": 3, "label": "Weekly", "label_pt": "Semanalmente"},
                    {"value": 4, "label": "Daily or almost daily", "label_pt": "Diariamente ou quase"}
                ]
            ),
            # Dependence symptoms (Questions 4-6)
            AssessmentQuestion(
                question_id="audit_4",
                text="How often during the last year have you found that you were not able to stop drinking once you had started?",
                text_pt="Com que frequência, no último ano, você não conseguiu parar de beber após começar?",
                category="dependence_symptoms",
                options=[
                    {"value": 0, "label": "Never", "label_pt": "Nunca"},
                    {"value": 1, "label": "Less than monthly", "label_pt": "Menos que mensalmente"},
                    {"value": 2, "label": "Monthly", "label_pt": "Mensalmente"},
                    {"value": 3, "label": "Weekly", "label_pt": "Semanalmente"},
                    {"value": 4, "label": "Daily or almost daily", "label_pt": "Diariamente ou quase"}
                ]
            ),
            AssessmentQuestion(
                question_id="audit_5",
                text="How often during the last year have you failed to do what was normally expected of you because of drinking?",
                text_pt="Com que frequência, no último ano, você não conseguiu fazer o que era esperado devido ao álcool?",
                category="dependence_symptoms",
                options=[
                    {"value": 0, "label": "Never", "label_pt": "Nunca"},
                    {"value": 1, "label": "Less than monthly", "label_pt": "Menos que mensalmente"},
                    {"value": 2, "label": "Monthly", "label_pt": "Mensalmente"},
                    {"value": 3, "label": "Weekly", "label_pt": "Semanalmente"},
                    {"value": 4, "label": "Daily or almost daily", "label_pt": "Diariamente ou quase"}
                ]
            ),
            AssessmentQuestion(
                question_id="audit_6",
                text="How often during the last year have you needed a first drink in the morning to get yourself going after a heavy drinking session?",
                text_pt="Com que frequência, no último ano, você precisou beber pela manhã para se sentir bem após ter bebido muito?",
                category="dependence_symptoms",
                options=[
                    {"value": 0, "label": "Never", "label_pt": "Nunca"},
                    {"value": 1, "label": "Less than monthly", "label_pt": "Menos que mensalmente"},
                    {"value": 2, "label": "Monthly", "label_pt": "Mensalmente"},
                    {"value": 3, "label": "Weekly", "label_pt": "Semanalmente"},
                    {"value": 4, "label": "Daily or almost daily", "label_pt": "Diariamente ou quase"}
                ]
            ),
            # Harmful alcohol use (Questions 7-10)
            AssessmentQuestion(
                question_id="audit_7",
                text="How often during the last year have you had a feeling of guilt or remorse after drinking?",
                text_pt="Com que frequência, no último ano, você se sentiu culpado ou com remorso após beber?",
                category="harmful_use",
                options=[
                    {"value": 0, "label": "Never", "label_pt": "Nunca"},
                    {"value": 1, "label": "Less than monthly", "label_pt": "Menos que mensalmente"},
                    {"value": 2, "label": "Monthly", "label_pt": "Mensalmente"},
                    {"value": 3, "label": "Weekly", "label_pt": "Semanalmente"},
                    {"value": 4, "label": "Daily or almost daily", "label_pt": "Diariamente ou quase"}
                ]
            ),
            AssessmentQuestion(
                question_id="audit_8",
                text="How often during the last year have you been unable to remember what happened the night before because of your drinking?",
                text_pt="Com que frequência, no último ano, você não conseguiu lembrar do que aconteceu na noite anterior por causa da bebida?",
                category="harmful_use",
                options=[
                    {"value": 0, "label": "Never", "label_pt": "Nunca"},
                    {"value": 1, "label": "Less than monthly", "label_pt": "Menos que mensalmente"},
                    {"value": 2, "label": "Monthly", "label_pt": "Mensalmente"},
                    {"value": 3, "label": "Weekly", "label_pt": "Semanalmente"},
                    {"value": 4, "label": "Daily or almost daily", "label_pt": "Diariamente ou quase"}
                ]
            ),
            AssessmentQuestion(
                question_id="audit_9",
                text="Have you or someone else been injured because of your drinking?",
                text_pt="Você ou alguém já se machucou devido ao seu consumo de álcool?",
                category="harmful_use",
                options=[
                    {"value": 0, "label": "No", "label_pt": "Não"},
                    {"value": 2, "label": "Yes, but not in the last year", "label_pt": "Sim, mas não no último ano"},
                    {"value": 4, "label": "Yes, during the last year", "label_pt": "Sim, no último ano"}
                ]
            ),
            AssessmentQuestion(
                question_id="audit_10",
                text="Has a relative, friend, doctor, or other health care worker been concerned about your drinking or suggested you cut down?",
                text_pt="Algum parente, amigo, médico ou profissional de saúde já se preocupou com seu consumo de álcool ou sugeriu que você parasse?",
                category="harmful_use",
                options=[
                    {"value": 0, "label": "No", "label_pt": "Não"},
                    {"value": 2, "label": "Yes, but not in the last year", "label_pt": "Sim, mas não no último ano"},
                    {"value": 4, "label": "Yes, during the last year", "label_pt": "Sim, no último ano"}
                ]
            )
        ]
        
        return questions
    
    def calculate_severity(self) -> Tuple[SeverityLevel, str]:
        """Calculate AUDIT severity and risk level."""
        score = self.total_score
        
        # WHO guidelines for AUDIT interpretation
        if score <= 7:
            severity = SeverityLevel.NONE
            risk = "Low Risk"
            self.intervention_recommendation = "Alcohol education"
        elif score <= 15:
            severity = SeverityLevel.MILD
            risk = "Moderate Risk"
            self.intervention_recommendation = "Simple advice"
        elif score <= 19:
            severity = SeverityLevel.MODERATE
            risk = "High Risk"
            self.intervention_recommendation = "Simple advice plus brief counseling and continued monitoring"
        else:
            severity = SeverityLevel.SEVERE
            risk = "Very High Risk"
            self.intervention_recommendation = "Referral to specialist for diagnostic evaluation and treatment"
        
        self.drinking_risk_level = risk
        return severity, f"AUDIT Score: {score} - {risk}"


class DAST10Assessment(MentalHealthAssessment):
    """Drug Abuse Screening Test (10 items) - Brief screening for drug use problems."""
    
    assessment_type: AssessmentType = Field(default=AssessmentType.DAST10, frozen=True)
    
    # DAST-10 specific fields
    drug_use_problem_level: str  # None, Low, Moderate, Substantial, Severe
    intervention_level: Optional[EncryptedStr] = None
    
    @classmethod
    def get_questions(cls) -> List[AssessmentQuestion]:
        """Get DAST-10 questions."""
        # Standard Yes/No options for most DAST-10 questions
        yes_no_options = [
            {"value": 0, "label": "No", "label_pt": "Não"},
            {"value": 1, "label": "Yes", "label_pt": "Sim"}
        ]
        
        questions = [
            AssessmentQuestion(
                question_id="dast10_1",
                text="Have you used drugs other than those required for medical reasons?",
                text_pt="Você usou drogas além daquelas prescritas por razões médicas?",
                category="drug_use",
                options=yes_no_options
            ),
            AssessmentQuestion(
                question_id="dast10_2",
                text="Do you use more than one drug at a time?",
                text_pt="Você usa mais de uma droga ao mesmo tempo?",
                category="drug_use",
                options=yes_no_options
            ),
            AssessmentQuestion(
                question_id="dast10_3",
                text="Are you always able to stop using drugs when you want to?",
                text_pt="Você sempre consegue parar de usar drogas quando quer?",
                category="control",
                options=[
                    {"value": 1, "label": "No", "label_pt": "Não"},  # Reversed scoring
                    {"value": 0, "label": "Yes", "label_pt": "Sim"}
                ],
                clinical_note="Reversed scoring item"
            ),
            AssessmentQuestion(
                question_id="dast10_4",
                text="Have you had 'blackouts' or 'flashbacks' as a result of drug use?",
                text_pt="Você teve 'apagões' ou 'flashbacks' como resultado do uso de drogas?",
                category="consequences",
                options=yes_no_options
            ),
            AssessmentQuestion(
                question_id="dast10_5",
                text="Do you ever feel bad or guilty about your drug use?",
                text_pt="Você já se sentiu mal ou culpado sobre seu uso de drogas?",
                category="psychological",
                options=yes_no_options
            ),
            AssessmentQuestion(
                question_id="dast10_6",
                text="Does your spouse (or parents) ever complain about your involvement with drugs?",
                text_pt="Seu cônjuge (ou pais) já reclamou sobre seu envolvimento com drogas?",
                category="social",
                options=yes_no_options
            ),
            AssessmentQuestion(
                question_id="dast10_7",
                text="Have you neglected your family because of your use of drugs?",
                text_pt="Você negligenciou sua família por causa do uso de drogas?",
                category="social",
                options=yes_no_options
            ),
            AssessmentQuestion(
                question_id="dast10_8",
                text="Have you engaged in illegal activities in order to obtain drugs?",
                text_pt="Você se envolveu em atividades ilegais para obter drogas?",
                category="legal",
                options=yes_no_options
            ),
            AssessmentQuestion(
                question_id="dast10_9",
                text="Have you ever experienced withdrawal symptoms (felt sick) when you stopped taking drugs?",
                text_pt="Você já teve sintomas de abstinência (sentiu-se mal) quando parou de usar drogas?",
                category="physical",
                options=yes_no_options
            ),
            AssessmentQuestion(
                question_id="dast10_10",
                text="Have you had medical problems as a result of your drug use (e.g., memory loss, hepatitis, convulsions, bleeding)?",
                text_pt="Você teve problemas médicos como resultado do uso de drogas (ex: perda de memória, hepatite, convulsões, sangramento)?",
                category="medical",
                options=yes_no_options
            )
        ]
        
        return questions
    
    def calculate_severity(self) -> Tuple[SeverityLevel, str]:
        """Calculate DAST-10 severity and problem level."""
        score = self.total_score
        
        # DAST-10 interpretation guidelines
        if score == 0:
            severity = SeverityLevel.NONE
            problem_level = "No problems reported"
            self.intervention_level = "No intervention"
        elif score <= 2:
            severity = SeverityLevel.MINIMAL
            problem_level = "Low level"
            self.intervention_level = "Monitor, re-assess at a later date"
        elif score <= 4:
            severity = SeverityLevel.MILD
            problem_level = "Moderate level"
            self.intervention_level = "Further investigation"
        elif score <= 7:
            severity = SeverityLevel.MODERATE
            problem_level = "Substantial level"
            self.intervention_level = "Intensive assessment"
        else:
            severity = SeverityLevel.SEVERE
            problem_level = "Severe level"
            self.intervention_level = "Intensive assessment"
        
        self.drug_use_problem_level = problem_level
        return severity, f"DAST-10 Score: {score} - {problem_level}"


class CAGEAssessment(MentalHealthAssessment):
    """CAGE Questionnaire - Brief 4-item alcoholism screening tool."""
    
    assessment_type: AssessmentType = Field(default=AssessmentType.CAGE, frozen=True)
    
    # CAGE specific fields
    positive_screens: int  # Number of positive responses
    alcoholism_screening_result: str  # Negative, Possible, Probable
    
    @classmethod
    def get_questions(cls) -> List[AssessmentQuestion]:
        """Get CAGE questions."""
        yes_no_options = [
            {"value": 0, "label": "No", "label_pt": "Não"},
            {"value": 1, "label": "Yes", "label_pt": "Sim"}
        ]
        
        questions = [
            AssessmentQuestion(
                question_id="cage_c",
                text="Have you ever felt you should Cut down on your drinking?",
                text_pt="Você já sentiu que deveria Cortar (diminuir) sua bebida?",
                category="screening",
                options=yes_no_options,
                clinical_note="C - Cut down"
            ),
            AssessmentQuestion(
                question_id="cage_a",
                text="Have people Annoyed you by criticizing your drinking?",
                text_pt="As pessoas já o Aborreceram criticando sua bebida?",
                category="screening",
                options=yes_no_options,
                clinical_note="A - Annoyed"
            ),
            AssessmentQuestion(
                question_id="cage_g",
                text="Have you ever felt bad or Guilty about your drinking?",
                text_pt="Você já se sentiu mal ou Culpado sobre sua bebida?",
                category="screening",
                options=yes_no_options,
                clinical_note="G - Guilty"
            ),
            AssessmentQuestion(
                question_id="cage_e",
                text="Have you ever had a drink first thing in the morning to steady your nerves or to get rid of a hangover (Eye opener)?",
                text_pt="Você já tomou bebida alcoólica pela manhã para Estabilizar os nervos ou se livrar de uma ressaca?",
                category="screening",
                options=yes_no_options,
                clinical_note="E - Eye opener"
            )
        ]
        
        return questions
    
    def calculate_severity(self) -> Tuple[SeverityLevel, str]:
        """Calculate CAGE severity and screening result."""
        score = self.total_score
        self.positive_screens = score
        
        # CAGE interpretation
        if score == 0:
            severity = SeverityLevel.NONE
            result = "Negative"
            interpretation = "No indication of alcohol problems"
        elif score == 1:
            severity = SeverityLevel.MINIMAL
            result = "Possible"
            interpretation = "Possible alcohol problem"
        else:  # score >= 2
            severity = SeverityLevel.MODERATE
            result = "Probable"
            interpretation = "Probable alcohol problem - further assessment recommended"
        
        self.alcoholism_screening_result = result
        return severity, f"CAGE Score: {score}/4 - {interpretation}"