<?php

namespace App\Classes\Modules\Anthropic\Services;


use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Exceptions\ConnectionErrorException;

class UploadsClaudeFiles
{
    public function execute(array $paths): array
    {
        try {
            $ids = [];

            foreach ($paths as $path) {
                $response = Http::withHeaders([
                    'x-api-key' => config('anthropic.api_key'),
                    'anthropic-version' => '2023-06-01',
                    'anthropic-beta' => 'files-api-2025-04-14',
                ])->attach(
                    'file',
                    fopen($path, 'r'),
                    basename($path)
                )->post(config('anthropic.base_url') . '/v1/files');

                $data = $response->json();

                if ($response->successful() && isset($data['id'])) {
                    $ids[] = $data['id'];
                } else {
                    Log::error('Claude file upload failed', [
                        'path' => $path,
                        'response' => $data,
                    ]);
                }
            }

            return $ids;
        }
        catch (\Illuminate\Http\Client\ConnectionException $exception) {
            $error = 'Failed to connect to Claude API';
            throw new ConnectionErrorException(
                $error,
                $exception->getMessage(),
                $exception->getTraceAsString()
            );
        }
        catch (\Exception $exception) {
            throw new MalformedRequestException(
                'Unable to get correct response from Claude API: ' . $exception->getMessage()
            );
        }
    }
}
