<?php
namespace boru\ai\Provider\Gemini;

use boru\ai\Asset\Asset;
use boru\ai\Asset\AssetProviderInterface;
use boru\ai\Asset\ProviderAssetBinding;

class GeminiAssetProvider implements AssetProviderInterface
{
    /** @var GeminiClient */
    protected $client;

    public function __construct(GeminiClient $client = null)
    {
        $this->client = $client ? $client : new GeminiClient();
    }

    public function providerName()
    {
        return 'gemini';
    }

    public function client(GeminiClient $client = null)
    {
        if ($client !== null) {
            $this->client = $client;
            return $this;
        }
        return $this->client;
    }

    public function ensureBinding(Asset $asset, $purpose = null, ProviderAssetBinding $existingBinding = null)
    {
        if ($existingBinding instanceof ProviderAssetBinding && ($existingBinding->providerUri() || $existingBinding->providerAssetId())) {
            return $existingBinding;
        }

        if (!$asset->path()) {
            throw new \InvalidArgumentException('Gemini asset upload requires a local asset path');
        }

        $mimeType = $asset->mimeType() ? $asset->mimeType() : 'application/octet-stream';
        $displayName = $asset->filename() ? $asset->filename() : basename($asset->path());
        $result = $this->client()->uploadFile($asset->path(), array(
            'mime_type' => $mimeType,
            'display_name' => $displayName,
        ));

        $file = isset($result['file']) && is_array($result['file']) ? $result['file'] : $result;
        $binding = $existingBinding ? $existingBinding : new ProviderAssetBinding();
        $binding->assetId($asset->id());
        $binding->provider($this->providerName());
        $binding->purpose($purpose);
        $binding->status(isset($file['state']) ? strtolower((string)$file['state']) : 'ready');
        $binding->mimeType(isset($file['mimeType']) ? $file['mimeType'] : $mimeType);
        $binding->raw($result);
        $binding->createdAt(date('c'));
        $binding->updatedAt(date('c'));

        if (isset($file['name'])) {
            $binding->providerAssetId($file['name']);
        }
        if (isset($file['uri'])) {
            $binding->providerUri($file['uri']);
        }
        if (isset($file['displayName'])) {
            $binding->metadata('display_name', $file['displayName']);
        }
        if (isset($file['mimeType'])) {
            $binding->metadata('uploaded_mime_type', $file['mimeType']);
        }
        if (isset($file['state'])) {
            $binding->metadata('remote_state', $file['state']);
        }
        if (isset($file['sizeBytes'])) {
            $binding->metadata('remote_size_bytes', $file['sizeBytes']);
        }

        return $binding;
    }
}
