<?php

namespace ZenoChatbot\Services\LLMService\AIClient\Support;

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

/**
 * Result container for loaded resources.
 * Separates text resources from file resources and tracks skipped files.
 */
class ResourceResult
{
    /** @var array Text-based resources (JSON indexes, inline text, etc.) */
    private array $textResources = [];

    /** @var FileResource[] File resources for native API injection */
    private array $fileResources = [];

    /** @var array Files skipped due to size limits or unsupported types */
    private array $skippedFiles = [];

    public function addTextResource(array $resource): void
    {
        $this->textResources[] = $resource;
    }

    public function addFileResource(FileResource $file): void
    {
        $this->fileResources[] = $file;
    }

    public function addSkippedFile(string $filename, string $reason): void
    {
        $this->skippedFiles[] = [
            'filename' => $filename,
            'reason' => $reason,
        ];
    }

    /**
     * @return array
     */
    public function getTextResources(): array
    {
        return $this->textResources;
    }

    /**
     * @return FileResource[]
     */
    public function getFileResources(): array
    {
        return $this->fileResources;
    }

    /**
     * @return array
     */
    public function getSkippedFiles(): array
    {
        return $this->skippedFiles;
    }

    public function hasSkippedFiles(): bool
    {
        return !empty($this->skippedFiles);
    }

    public function hasFileResources(): bool
    {
        return !empty($this->fileResources);
    }

    public function hasTextResources(): bool
    {
        return !empty($this->textResources);
    }

    /**
     * Get skipped filenames as a simple array
     */
    public function getSkippedFilenames(): array
    {
        return array_column($this->skippedFiles, 'filename');
    }

    /**
     * Merge another ResourceResult into this one
     */
    public function merge(ResourceResult $other): void
    {
        foreach ($other->getTextResources() as $resource) {
            $this->addTextResource($resource);
        }
        foreach ($other->getFileResources() as $file) {
            $this->addFileResource($file);
        }
        foreach ($other->getSkippedFiles() as $skipped) {
            $this->skippedFiles[] = $skipped;
        }
    }

    /**
     * Convert to array for payload building
     */
    public function toArray(): array
    {
        return [
            'text_resources' => $this->textResources,
            'file_resources' => array_map(fn(FileResource $f) => $f->toArray(), $this->fileResources),
            'skipped_files' => $this->skippedFiles,
        ];
    }
}

