<?php

namespace ZenoChatbot\Services\LLMService\AIClient\Support;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Represents a file resource for LLM API injection.
 * Handles images and PDFs with base64 encoding for native API support.
 */
class FileResource
{
    /** @var int Maximum file size in bytes (15MB) */
    public const MAX_FILE_SIZE = 15 * 1024 * 1024;

    /** @var array Supported MIME types for file injection */
    public const SUPPORTED_MIME_TYPES = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/webp',
        'application/pdf',
    ];

    private string $id;
    private string $name;
    private string $mimeType;
    private string $base64Data;
    private int $fileSize;
    private ?string $path;

    public function __construct(
        string $id,
        string $name,
        string $mimeType,
        string $base64Data,
        int $fileSize,
        ?string $path = null
    ) {
        $this->id = $id;
        $this->name = $name;
        $this->mimeType = $mimeType;
        $this->base64Data = $base64Data;
        $this->fileSize = $fileSize;
        $this->path = $path;
    }

    public function getId(): string
    {
        return $this->id;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getMimeType(): string
    {
        return $this->mimeType;
    }

    public function getBase64Data(): string
    {
        return $this->base64Data;
    }

    public function getFileSize(): int
    {
        return $this->fileSize;
    }

    public function getPath(): ?string
    {
        return $this->path;
    }

    public function isImage(): bool
    {
        return str_starts_with($this->mimeType, 'image/');
    }

    public function isPdf(): bool
    {
        return $this->mimeType === 'application/pdf';
    }

    /**
     * Get data URL for the file (data:mime;base64,...)
     */
    public function getDataUrl(): string
    {
        return sprintf('data:%s;base64,%s', $this->mimeType, $this->base64Data);
    }

    /**
     * Convert to array for serialization
     */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'mime_type' => $this->mimeType,
            'file_size' => $this->fileSize,
            'is_image' => $this->isImage(),
            'is_pdf' => $this->isPdf(),
        ];
    }

    /**
     * Check if a MIME type is supported for file injection
     */
    public static function isSupportedMimeType(string $mimeType): bool
    {
        return in_array($mimeType, static::SUPPORTED_MIME_TYPES, true);
    }

    /**
     * Check if file size is within limits
     */
    public static function isWithinSizeLimit(int $fileSize): bool
    {
        return $fileSize <= static::MAX_FILE_SIZE;
    }
}

