"""
Ghostwriter Draft model.

Stores drafts generated by the Ghostwriter Agent.
"""

from datetime import datetime
from uuid import uuid4

from sqlalchemy import (
    JSON,
    Boolean,
    Column,
    DateTime,
    Float,
    ForeignKey,
    Index,
    Integer,
    String,
    Text,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship

from src.core.database import Base


class GhostwriterDraft(Base):
    """
    Ghostwriter generated draft.

    Stores drafts created by the Ghostwriter Agent along with
    metadata, sources, and user feedback.
    """

    __tablename__ = "ghostwriter_drafts"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
    tenant_id = Column(UUID(as_uuid=True), ForeignKey("tenants.id"), nullable=False)
    agent_id = Column(UUID(as_uuid=True), ForeignKey("agents.id"))

    # Request details
    content_type = Column(String, nullable=False)  # email, brief, proposal, etc.
    person_identifier = Column(String, nullable=False)  # Who to emulate
    topic = Column(Text, nullable=False)
    purpose = Column(Text)
    additional_context = Column(Text)
    tone_adjustment = Column(String)  # more_formal, more_casual, etc.

    # Generated content
    draft_content = Column(Text, nullable=False)
    style_profile_id = Column(UUID(as_uuid=True), ForeignKey("writing_style_profiles.id"))

    # Metadata
    sources_used = Column(JSON, default=list)  # List of source references
    confidence_score = Column(Float, default=0.0)  # 0-1
    generation_time_ms = Column(Integer)
    model_used = Column(String)
    provider_used = Column(String)

    # User feedback
    user_rating = Column(Integer)  # 1-5
    user_feedback = Column(Text)
    was_edited = Column(Boolean, default=False)
    final_version = Column(Text)  # If user edited

    # Timestamps
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # Relationships
    style_profile = relationship("WritingStyleProfile", back_populates="drafts")

    # Indexes
    __table_args__ = (
        Index("idx_ghostwriter_draft_tenant", "tenant_id"),
        Index("idx_ghostwriter_draft_agent", "agent_id"),
        Index("idx_ghostwriter_draft_person", "person_identifier"),
        Index("idx_ghostwriter_draft_style_profile", "style_profile_id"),
        Index("idx_ghostwriter_draft_created", "created_at"),
    )

    def __repr__(self) -> str:
        """String representation."""
        return (
            f"<GhostwriterDraft "
            f"id={self.id} "
            f"type={self.content_type} "
            f"person={self.person_identifier} "
            f"confidence={self.confidence_score:.2f}>"
        )

    def to_dict(self) -> dict:
        """Convert to dictionary."""
        return {
            "id": str(self.id),
            "tenant_id": str(self.tenant_id),
            "agent_id": str(self.agent_id) if self.agent_id else None,
            "content_type": self.content_type,
            "person_identifier": self.person_identifier,
            "topic": self.topic,
            "purpose": self.purpose,
            "additional_context": self.additional_context,
            "tone_adjustment": self.tone_adjustment,
            "draft_content": self.draft_content,
            "style_profile_id": str(self.style_profile_id) if self.style_profile_id else None,
            "sources_used": self.sources_used,
            "confidence_score": self.confidence_score,
            "generation_time_ms": self.generation_time_ms,
            "model_used": self.model_used,
            "provider_used": self.provider_used,
            "user_rating": self.user_rating,
            "user_feedback": self.user_feedback,
            "was_edited": self.was_edited,
            "final_version": self.final_version,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
        }
