from __future__ import annotations

from datetime import datetime
from typing import Any, Literal, Optional

from pydantic import BaseModel, Field


MomStageAnswer = Literal["expecting", "parenting", "unknown"]
EmotionAnswer = Literal["low", "overwhelmed", "tired", "neutral", "calm", "joyful"]
ContextAnswer = Literal["family", "work", "relationship", "friends", "health"]
NeedAnswer = Literal[
    "emotional_support",
    "parenting_pressure",
    "self_worth",
    "anxiety_relief",
    "rest_balance",
]


class QuestionnaireAnswersV1_2(BaseModel):
    """
    V1.2：每题可跳过

    说明：
    - `None` 表示题目被跳过/无值（与客户端的 `null` 对齐）
    - 字段缺失（未传）也视为跳过
    """

    mom_stage: Optional[MomStageAnswer] = None
    emotion: Optional[EmotionAnswer] = None
    context: Optional[ContextAnswer] = None
    need: Optional[NeedAnswer] = None


class ProfileAnswered(BaseModel):
    stage: bool
    emotion: bool
    context: bool
    need: bool


class UserStageOneHot(BaseModel):
    expecting: Optional[Literal[0, 1]] = None
    parenting: Optional[Literal[0, 1]] = None
    unknown: Literal[0, 1]


class ForbiddenContentPredicate(BaseModel):
    """
    用于表达“需要同时看用户与内容字段才能执行”的规则（跨维度规则）。
    """

    id: str
    when_user: dict[str, Any] = Field(default_factory=dict)
    forbid_content: dict[str, Any] = Field(default_factory=dict)


class HardRules(BaseModel):
    forbidden_risk_flags: list[str] = Field(default_factory=list)
    forbidden_content_predicates: list[ForbiddenContentPredicate] = Field(default_factory=list)


class UserProfileV1_2(BaseModel):
    profile_version: Literal["v1.2"] = "v1.2"
    profile_source: Literal["questionnaire"] = "questionnaire"
    profile_generated_at: datetime
    profile_confidence: float
    profile_answered: ProfileAnswered
    stage: UserStageOneHot
    emotion_score: Optional[float] = None
    context: dict[str, Literal[1]] = Field(default_factory=dict)
    need: dict[str, Literal[1]] = Field(default_factory=dict)


class UserProfileV1_2_Extended(UserProfileV1_2):
    rule_hits: list[str] = Field(default_factory=list)
    hard_rules: HardRules = Field(default_factory=HardRules)


class BuildUserProfileRequest(BaseModel):
    """
    API 请求体：问卷答案 + 可选时间注入（便于回归测试/服务端批处理）
    """

    answers: QuestionnaireAnswersV1_2 = Field(default_factory=QuestionnaireAnswersV1_2)
    generated_at: Optional[datetime] = None
    now: Optional[datetime] = None

