<?php

namespace ZenoChatbot\Helper;

/**
 * Media Resources Manager
 * Manages WordPress Media Library attachments for LLM context
 */
class MediaResources
{
    private static string $settingsKey = 'data_source.media_resources';

    /**
     * Allowed MIME types for resources (images and PDFs only)
     */
    private static array $allowedMimeTypes = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/webp',
        'application/pdf',
    ];

    /**
     * Get all media resources with attachment metadata
     *
     * @return array
     */
    public static function getAll(): array
    {
        $resourceIds = Settings::get(static::$settingsKey, []);

        if (!is_array($resourceIds) || empty($resourceIds)) {
            return [];
        }

        $resources = [];

        foreach ($resourceIds as $attachmentId) {
            $attachment = get_post($attachmentId);

            if (!$attachment || $attachment->post_type !== 'attachment') {
                continue;
            }

            $filePath = get_attached_file($attachmentId);
            $fileSize = $filePath && file_exists($filePath) ? filesize($filePath) : 0;

            $resources[] = [
                'id' => (int) $attachmentId,
                'title' => $attachment->post_title,
                'filename' => basename(get_attached_file($attachmentId)),
                'url' => wp_get_attachment_url($attachmentId),
                'mime_type' => $attachment->post_mime_type,
                'file_size' => $fileSize,
                'file_size_formatted' => size_format($fileSize),
                'date_added' => $attachment->post_date,
                'thumbnail' => static::getThumbnail($attachmentId, $attachment->post_mime_type),
            ];
        }

        return $resources;
    }

    /**
     * Add a media resource by attachment ID
     *
     * @param int $attachmentId
     * @return array{success: bool, message: string}
     */
    public static function add(int $attachmentId): array
    {
        $attachment = get_post($attachmentId);

        if (!$attachment || $attachment->post_type !== 'attachment') {
            return ['success' => false, 'message' => 'Invalid attachment ID'];
        }

        if (!in_array($attachment->post_mime_type, static::$allowedMimeTypes, true)) {
            return ['success' => false, 'message' => 'File type not allowed'];
        }

        $resourceIds = Settings::get(static::$settingsKey, []);

        if (!is_array($resourceIds)) {
            $resourceIds = [];
        }

        if (in_array($attachmentId, $resourceIds, true)) {
            return ['success' => false, 'message' => 'Resource already exists'];
        }

        $resourceIds[] = $attachmentId;
        Settings::update(static::$settingsKey, $resourceIds);

        return ['success' => true, 'message' => 'Resource added successfully'];
    }

    /**
     * Add multiple media resources
     *
     * @param array $attachmentIds
     * @return array{success: bool, message: string, added: int, skipped: int}
     */
    public static function addMultiple(array $attachmentIds): array
    {
        $added = 0;
        $skipped = 0;

        foreach ($attachmentIds as $attachmentId) {
            $result = static::add((int) $attachmentId);
            if ($result['success']) {
                $added++;
            } else {
                $skipped++;
            }
        }

        return [
            'success' => $added > 0,
            'message' => sprintf('%d resource(s) added, %d skipped', $added, $skipped),
            'added' => $added,
            'skipped' => $skipped,
        ];
    }

    /**
     * Remove a media resource
     *
     * @param int $attachmentId
     * @return bool
     */
    public static function remove(int $attachmentId): bool
    {
        $resourceIds = Settings::get(static::$settingsKey, []);

        if (!is_array($resourceIds)) {
            return false;
        }

        $key = array_search($attachmentId, $resourceIds, true);

        if ($key === false) {
            return false;
        }

        unset($resourceIds[$key]);
        $resourceIds = array_values($resourceIds);

        Settings::update(static::$settingsKey, $resourceIds);

        return true;
    }

    /**
     * Check if a resource exists
     *
     * @param int $attachmentId
     * @return bool
     */
    public static function exists(int $attachmentId): bool
    {
        $resourceIds = Settings::get(static::$settingsKey, []);

        return is_array($resourceIds) && in_array($attachmentId, $resourceIds, true);
    }

    /**
     * Get allowed MIME types
     *
     * @return array
     */
    public static function getAllowedMimeTypes(): array
    {
        return static::$allowedMimeTypes;
    }

    /**
     * Get resource count
     *
     * @return int
     */
    public static function count(): int
    {
        $resourceIds = Settings::get(static::$settingsKey, []);

        return is_array($resourceIds) ? count($resourceIds) : 0;
    }

    /**
     * Get thumbnail URL for an attachment
     *
     * @param int $attachmentId
     * @param string $mimeType
     * @return string
     */
    private static function getThumbnail(int $attachmentId, string $mimeType): string
    {
        if (strpos($mimeType, 'image/') === 0) {
            $thumbnail = wp_get_attachment_image_src($attachmentId, 'thumbnail');
            return $thumbnail ? $thumbnail[0] : '';
        }

        return '';
    }

    /**
     * Get allowed file extensions for frontend display
     *
     * @return array
     */
    public static function getAllowedExtensions(): array
    {
        return ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'];
    }

    /**
     * Get resources for LLM context (file paths only)
     *
     * @return array
     */
    public static function getResourcePaths(): array
    {
        $resourceIds = Settings::get(static::$settingsKey, []);

        if (!is_array($resourceIds) || empty($resourceIds)) {
            return [];
        }

        $paths = [];

        foreach ($resourceIds as $attachmentId) {
            $filePath = get_attached_file($attachmentId);

            if ($filePath && file_exists($filePath)) {
                $paths[] = $filePath;
            }
        }

        return $paths;
    }
}

