import uuid
from datetime import datetime

from sqlalchemy import String, Uuid, JSON, Float, Text, ForeignKey, Index, func
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class DiagnosisRecord(Base):
    __tablename__ = "diagnosis_records"

    id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    brand_id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        ForeignKey("brands.id", ondelete="CASCADE"),
        nullable=False,
    )
    user_id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), nullable=False)
    diagnosis_type: Mapped[str] = mapped_column(
        String(20), default="geo", nullable=False
    )
    status: Mapped[str] = mapped_column(String(20), default="pending", nullable=False)
    overall_score: Mapped[float | None] = mapped_column(Float, nullable=True)
    result_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
    collection_metadata: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        server_default=func.now(), nullable=False
    )
    completed_at: Mapped[datetime | None] = mapped_column(nullable=True)

    __table_args__ = (
        Index("idx_diagnosis_records_brand_id", "brand_id"),
        Index("idx_diagnosis_records_user_id", "user_id"),
        Index("idx_diagnosis_records_status", "status"),
        Index("idx_diagnosis_records_created_at", "created_at"),
    )
