"""Models for attachment operations."""

from typing import Optional
from pydantic import BaseModel, Field, validator
import base64


class AttachmentWrapper(BaseModel):
    """Wrapper for attachment data."""
    
    AttachmentName: str = Field(..., description="Name of the attachment file")
    AttachmentBytes: str = Field(..., description="Base64 encoded file bytes")
    IsSensitive: bool = Field(False, description="Whether to encrypt the attachment")
    
    @validator('AttachmentBytes')
    def validate_base64(cls, v):
        """Validate that AttachmentBytes is valid base64."""
        try:
            base64.b64decode(v)
        except Exception:
            raise ValueError("AttachmentBytes must be valid base64 encoded string")
        return v
    
    @classmethod
    def from_file(cls, filepath: str, is_sensitive: bool = False) -> "AttachmentWrapper":
        """
        Create AttachmentWrapper from a file path.
        
        Args:
            filepath: Path to the file
            is_sensitive: Whether to mark as sensitive/encrypted
            
        Returns:
            AttachmentWrapper instance
            
        Example:
            >>> attachment = AttachmentWrapper.from_file("document.pdf", is_sensitive=True)
        """
        import os
        
        filename = os.path.basename(filepath)
        
        with open(filepath, "rb") as f:
            file_bytes = f.read()
            encoded_bytes = base64.b64encode(file_bytes).decode('utf-8')
        
        return cls(
            AttachmentName=filename,
            AttachmentBytes=encoded_bytes,
            IsSensitive=is_sensitive
        )
    
    def save_to_file(self, output_path: str) -> None:
        """
        Save attachment bytes to a file.
        
        Args:
            output_path: Path where to save the file
            
        Example:
            >>> attachment.save_to_file("downloaded_document.pdf")
        """
        decoded_bytes = base64.b64decode(self.AttachmentBytes)
        
        with open(output_path, "wb") as f:
            f.write(decoded_bytes)


class AttachmentUploadRequest(BaseModel):
    """Request for uploading an attachment."""
    
    ContentId: int = Field(..., description="Content record ID")
    FieldId: int = Field(..., description="Attachment field ID")
    AttachmentName: str = Field(..., description="File name")
    IsSensitive: bool = Field(False, description="Encrypt the file")


class AttachmentResponse(BaseModel):
    """Response from attachment operations."""
    
    Links: list = Field(default_factory=list)
    RequestedObject: dict = Field(default_factory=dict)
    IsSuccessful: bool
    ValidationMessages: list = Field(default_factory=list)
    
    @property
    def attachment_id(self) -> Optional[int]:
        """Extract attachment ID from response."""
        return self.RequestedObject.get("Id")