from datetime import datetime

from sqlalchemy import DateTime, ForeignKey, Integer, String, Text, Float
from sqlalchemy.orm import Mapped, mapped_column

from app.models.base import Base, TimestampMixin, SoftDeleteMixin


class GenerationRecord(Base, TimestampMixin, SoftDeleteMixin):
    __tablename__ = "generation_records"

    id: Mapped[str] = mapped_column(String(32), primary_key=True)
    user_id: Mapped[str] = mapped_column(
        String(32), ForeignKey("users.id", ondelete="CASCADE"), index=True
    )
    project_id: Mapped[str] = mapped_column(
        String(32), ForeignKey("projects.id", ondelete="CASCADE"), index=True
    )
    original_prompt: Mapped[str] = mapped_column(Text)
    optimized_prompt: Mapped[str | None] = mapped_column(Text, nullable=True)
    gen_type: Mapped[str] = mapped_column(String(16), default="video")
    duration: Mapped[int | None] = mapped_column(Integer, nullable=True)
    aspect_ratio: Mapped[str | None] = mapped_column(String(8), nullable=True)
    resolution: Mapped[str | None] = mapped_column(String(8), nullable=True)
    image_size: Mapped[str | None] = mapped_column(String(8), nullable=True)
    image_proportion: Mapped[str | None] = mapped_column(String(8), nullable=True)
    image_px: Mapped[str | None] = mapped_column(String(10), nullable=True)

    status: Mapped[str] = mapped_column(String(32), default="prompt_optimized")
    video_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
    video_cover_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
    image_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
    media_references: Mapped[str | None] = mapped_column(Text, nullable=True)
    video_url_expires_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    seedance_task_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
    credits_cost: Mapped[float] = mapped_column(Float, default=0.0)
    text_credits_cost: Mapped[float] = mapped_column(Float, default=0.0)
    text_tokens_used: Mapped[int] = mapped_column(Integer, default=0)
    video_tokens_used: Mapped[int] = mapped_column(Integer, default=0)
    image_tokens_used: Mapped[int] = mapped_column(Integer, default=0)
    generated_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
    idempotency_key: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
