from __future__ import annotations

from datetime import datetime

from pydantic import BaseModel, Field, field_validator


class AttachmentAssociationJobCreate(BaseModel):
    receipt_ids: list[str] = Field(default_factory=list, description="票据夹持久化票据 ID。")
    prompt: str = Field(default="", max_length=1000, description="用户发送时的上下文说明。")
    conversation_id: str = Field(
        default="", max_length=120, description="前端会话 ID，用于状态恢复。"
    )

    @field_validator("receipt_ids")
    @classmethod
    def validate_receipt_ids(cls, value: list[str]) -> list[str]:
        receipt_ids = [
            str(item or "").strip() for item in list(value or []) if str(item or "").strip()
        ]
        if not receipt_ids:
            raise ValueError("请先完成附件 OCR 识别，再发起自动关联。")
        return list(dict.fromkeys(receipt_ids))


class AttachmentAssociationCandidateRead(BaseModel):
    target_type: str = "reimbursement_draft"
    expense_case_id: str = ""
    application_claim_id: str = ""
    application_claim_no: str = ""
    claim_id: str = ""
    claim_no: str = ""
    confidence: str = "low"
    score: float = 0.0
    match_reasons: list[str] = Field(default_factory=list)


class AttachmentAssociationJobRead(BaseModel):
    job_id: str
    status: str
    message: str = ""
    receipt_ids: list[str] = Field(default_factory=list)
    claim_id: str = ""
    claim_no: str = ""
    uploaded_count: int = 0
    skipped_count: int = 0
    resolution: str = "pending"
    requires_confirmation: bool = False
    expense_case_id: str = ""
    application_claim_id: str = ""
    application_claim_no: str = ""
    confidence: str = ""
    confidence_score: float = 0.0
    match_reasons: list[str] = Field(default_factory=list)
    exceptions: list[str] = Field(default_factory=list)
    missing_fields: list[str] = Field(default_factory=list)
    risk_items: list[str] = Field(default_factory=list)
    candidates: list[AttachmentAssociationCandidateRead] = Field(default_factory=list)
    draft_payload: dict[str, object] | None = None
    error: str = ""
    prompt: str = ""
    conversation_id: str = ""
    created_at: datetime
    updated_at: datetime
