"""Worklog model — immutable internal time-tracking records."""

# Import uuid
import uuid

# Import Column, DateTime, ForeignKey, Index, Integer, S... from sqlalchemy
from sqlalchemy import Column, DateTime, ForeignKey, Index, Integer, String, Text, func

# Import JSONB, UUID from sqlalchemy.dialects.postgresql
from sqlalchemy.dialects.postgresql import JSONB, UUID

# Import relationship from sqlalchemy.orm
from sqlalchemy.orm import relationship

# Import Base from app.database
from app.database import Base


# Define class Worklog
class Worklog(Base):
    """Internal worklog entry with integrity hash for audit compliance.

    Each worklog is tied to an Aegis entity (test, campaign, etc.) and
    optionally synced to Tempo.  The ``integrity_hash`` is a SHA-256 of
    the immutable fields so tampering can be detected.
    """

    # Assign __tablename__ = "worklogs"
    __tablename__ = "worklogs"

    # Assign id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    # Assign entity_type = Column(String(50), nullable=False)
    entity_type = Column(String(50), nullable=False)
    # Assign entity_id = Column(UUID(as_uuid=True), nullable=False)
    entity_id = Column(UUID(as_uuid=True), nullable=False)
    # Assign user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
    # Assign activity_type = Column(String(100), nullable=False)
    activity_type = Column(String(100), nullable=False)
    # Assign started_at = Column(DateTime, nullable=False)
    started_at = Column(DateTime, nullable=False)
    # Assign ended_at = Column(DateTime)
    ended_at = Column(DateTime)
    # Assign duration_seconds = Column(Integer, nullable=False)
    duration_seconds = Column(Integer, nullable=False)
    # Assign description = Column(Text)
    description = Column(Text)
    # Assign tempo_synced = Column(DateTime)
    tempo_synced = Column(DateTime)
    # Assign tempo_worklog_id = Column(String(100))
    tempo_worklog_id = Column(String(100))
    # Assign integrity_hash = Column(String(64))
    integrity_hash = Column(String(64))
    # Assign created_at = Column(DateTime(timezone=True), server_default=func.now())
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    # Assign extra_metadata = Column("metadata", JSONB, default={})
    extra_metadata = Column("metadata", JSONB, default={})

    # Assign user = relationship("User", foreign_keys=[user_id])
    user = relationship("User", foreign_keys=[user_id])

    # Assign __table_args__ = (
    __table_args__ = (
        Index("ix_worklogs_entity_id", "entity_id"),
        Index("ix_worklogs_user_id", "user_id"),
        Index("ix_worklogs_entity_type_entity_id", "entity_type", "entity_id"),
    )
