"""Database models for FenLiu."""

from sqlalchemy import JSON
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func

from fenliu.database import Base


class HashtagStream(Base):
    """Model for monitored hashtag streams."""

    __tablename__ = "hashtag_streams"

    id = Column(Integer, primary_key=True, index=True)
    hashtag = Column(String(100), nullable=False, index=True, unique=True)
    instance = Column(String(200), nullable=False, default="mastodon.social")
    active = Column(Boolean, default=True)
    last_check = Column(DateTime(timezone=True))
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    posts = relationship("Post", back_populates="stream", cascade="all, delete-orphan")

    def __repr__(self) -> str:
        """Return string representation of HashtagStream."""
        return f"HashtagStream(id={self.id}, hashtag='{self.hashtag}', instance='{self.instance}')"


class Post(Base):
    """Model for Fediverse posts."""

    __tablename__ = "posts"

    id = Column(Integer, primary_key=True, index=True)
    post_id = Column(String(100), nullable=False, index=True, unique=True)
    content = Column(Text, nullable=False)
    author_username = Column(String(100))
    author_display_name = Column(String(200))
    author_url = Column(String(500))
    instance = Column(String(200), nullable=False)
    hashtags = Column(JSON)
    boosts = Column(Integer, default=0)
    likes = Column(Integer, default=0)
    replies = Column(Integer, default=0)
    url = Column(String(500))
    created_at = Column(DateTime(timezone=True))
    fetched_at = Column(DateTime(timezone=True), server_default=func.now())
    processed = Column(Boolean, default=False)
    spam_score = Column(Integer, default=0)  # 0-100 scale

    stream_id = Column(Integer, ForeignKey("hashtag_streams.id"))
    stream = relationship("HashtagStream", back_populates="posts")

    def __repr__(self) -> str:
        """Return string representation of Post."""
        return f"Post(id={self.id}, post_id='{self.post_id}', author='{self.author_username}')"
