"""Comment model for ticket discussions."""

from typing import Optional, List

from pydantic import Field, field_validator, model_validator

from gira.models.base import TimestampedModel


class Comment(TimestampedModel):
    """Represents a comment on a ticket."""

    id: str = Field(
        ...,
        description="Unique comment ID (e.g., UUID or timestamp-based)"
    )
    ticket_id: Optional[str] = Field(
        None,
        pattern=r"^[A-Z]{2,4}-\d+$",
        description="Parent ticket ID (mutually exclusive with epic_id)"
    )
    epic_id: Optional[str] = Field(
        None,
        pattern=r"^EPIC-\d+$",
        description="Parent epic ID (mutually exclusive with ticket_id)"
    )
    author: str = Field(
        ...,
        description="Email or username of comment author"
    )
    content: str = Field(
        ...,
        min_length=1,
        description="Comment content in Markdown format"
    )

    # Edit tracking
    edited: bool = Field(
        default=False,
        description="Whether comment has been edited"
    )
    edit_count: int = Field(
        default=0,
        ge=0,
        description="Number of times edited"
    )

    # AI agent metadata
    is_ai_generated: bool = Field(
        default=False,
        description="Whether comment was generated by AI"
    )
    ai_model: Optional[str] = Field(
        default=None,
        description="AI model used if applicable"
    )
    
    # Attachments
    attachments: List[str] = Field(
        default_factory=list,
        description="List of attachment pointer filenames"
    )
    attachment_count: int = Field(
        default=0,
        ge=0,
        description="Number of attachments"
    )

    @field_validator("ticket_id", mode="before")
    @classmethod
    def uppercase_ticket_id(cls, v: Optional[str]) -> Optional[str]:
        """Ensure ticket ID is uppercase."""
        if isinstance(v, str):
            return v.upper()
        return v
    
    @field_validator("epic_id", mode="before")
    @classmethod
    def uppercase_epic_id(cls, v: Optional[str]) -> Optional[str]:
        """Ensure epic ID is uppercase."""
        if isinstance(v, str):
            return v.upper()
        return v
    
    @model_validator(mode="after")
    def validate_parent_id(self):
        """Ensure exactly one of ticket_id or epic_id is set."""
        if not self.ticket_id and not self.epic_id:
            raise ValueError("Either ticket_id or epic_id must be provided")
        if self.ticket_id and self.epic_id:
            raise ValueError("Only one of ticket_id or epic_id can be provided")
        return self

    def edit(self, new_content: str) -> None:
        """Edit the comment content."""
        if new_content != self.content:
            self.content = new_content
            self.edited = True
            self.edit_count += 1
            # Note: In practice, updated_at would be set by the persistence layer

    @classmethod
    def generate_id(cls) -> str:
        """Generate a unique comment ID."""
        import uuid
        from datetime import datetime

        # Use timestamp + short UUID for readable, sortable IDs
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        short_uuid = str(uuid.uuid4())[:8]
        return f"{timestamp}-{short_uuid}"
