<?php

namespace ZenoChatbot\Services\LLMService\AIClient\Support\Handlers;

use ZenoChatbot\Services\LLMService\AIClient\Support\FileResource;
use ZenoChatbot\Services\LLMService\AIClient\Support\ResourceResult;
use ZenoChatbot\Helper\MediaResources;

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

/**
 * Handles loading media resources from WordPress Media Library.
 */
class MediaHandler
{
    /**
     * Load all media resources from MediaResources helper
     */
    public static function loadAll(ResourceResult $result, array $options = []): void
    {
        if (!class_exists(MediaResources::class)) {
            return;
        }

        $mediaItems = MediaResources::getAll();

        foreach ($mediaItems as $item) {
            static::loadItem($item, $result);
        }
    }

    /**
     * Load a single media item
     */
    private static function loadItem(array $item, ResourceResult $result): void
    {
        $attachmentId = (int) ($item['id'] ?? 0);
        $filename = $item['filename'] ?? ('attachment-' . $attachmentId);
        $mimeType = $item['mime_type'] ?? '';
        $fileSize = (int) ($item['file_size'] ?? 0);

        // Check if MIME type is supported
        if (!FileResource::isSupportedMimeType($mimeType)) {
            return; // Skip unsupported types
        }

        // Check file size before processing
        if (!FileResource::isWithinSizeLimit($fileSize)) {
            $result->addSkippedFile($filename, 'File exceeds 15MB size limit');
            return;
        }

        // Load the file
        $filePath = get_attached_file($attachmentId);
        if (!$filePath || !file_exists($filePath) || !is_readable($filePath)) {
            $result->addSkippedFile($filename, 'File not accessible');
            return;
        }

        // Read and encode file content
        $content = @file_get_contents($filePath);
        if ($content === false) {
            $result->addSkippedFile($filename, 'Failed to read file');
            return;
        }

        $result->addFileResource(new FileResource(
            (string) $attachmentId,
            $filename,
            $mimeType,
            base64_encode($content),
            $fileSize,
            $filePath
        ));
    }

    /**
     * Load a single attachment by ID
     */
    public static function loadAttachment(int $id, ResourceResult $result, array $options = []): void
    {
        $path = function_exists('get_attached_file') ? get_attached_file($id) : null;

        if (!$path || !is_string($path) || !file_exists($path)) {
            return;
        }

        FileHandler::load($path, $result, $options);
    }
}

