<?php

namespace App\Services;

use App\Facades\Settings;
use App\Models\ExternalServiceUsage;
use Illuminate\Support\Facades\Http;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleOffer;

class OpenAI
{
    public function __construct(protected readonly ExternalServiceUsage $usageService)
    {
        //
    }

    /**
     * Get AI generated description for a vehicle
     *
     * @param Vehicle|VehicleOffer $model
     */
    public function getDescription(Vehicle|VehicleOffer $model)
    {
        if (empty(Settings::get('open-ai-api_key'))) {
            return '';
        }

        $vehicleSpecs = array_filter(match (get_class($model)) {
            Vehicle::class => $this->getVehicleSpecs($model),
            VehicleOffer::class => $this->getVehicleOfferSpecs($model),
        });

        $prompt = Settings::get('open-ai-user_prompt') . ":\n\n"
            . implode("\n\n", $vehicleSpecs);

        $data = [
            'model' => config('services.open-ai.model'),
            //'temperature' => 0.7,
            //'max_tokens' => 200,
            'messages' => [
                [
                    'role' => 'system',
                    'content' => Settings::get('open-ai-system_prompt'),
                ],
                [
                    'role' => 'user',
                    'content' => $prompt,
                ],
            ],
        ];

        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . Settings::get('open-ai-api_key')
        ])
            ->post($this->endpoint('chat/completions'), $data);

        $this->usageService->logUsage(tenant('id'), 'open-ai', 'vehicle-description');

        return $response->successful() ? $response->json('choices.0.message.content') : '';
    }

    protected function endpoint(string $path): string
    {
        return config('services.open-ai.endpoint') . $path;
    }

    protected function getVehicleSpecs(Vehicle $vehicle): array
    {
        $specs = [
            'title' => $vehicle->title,
            'mileage' => $vehicle->odometer_mi . ' miles',
            'fuel' => $vehicle->fuelType?->name,
            'bodytype' => $vehicle->bodyStyle?->name,
            'make' => $vehicle->make?->name,
            'model' => $vehicle->model?->name,
            'derivative' => $vehicle->derivative,
            'transmission' => $vehicle->transmission?->name,
            'year' => $vehicle->manufacture_year,
            'colour' => $vehicle->colour,
            'doors' => $vehicle->door_count . ' doors',
            'enginesize' => $vehicle->engine_size_cc . ' cc',
        ];

        if (Settings::get('open-ai-generate-description-use-tech-data')) {
            $specs += $vehicle
                ->specs()
                ->pluck('description')
                ->toArray();
        }

        if (Settings::get('open-ai-generate-description-use-equipment')) {
            $specs += $vehicle
                ->equipment()
                ->pluck('description')
                ->toArray();
        }

        $specs += $vehicle
            ->features()
            ->pluck('name')
            ->toArray();

        return $specs;
    }

    protected function getVehicleOfferSpecs(VehicleOffer $vehicleOffer): array
    {
        $specs = [
            'title' => $vehicleOffer->name,
            'make' => $vehicleOffer->make?->name,
            'model' => $vehicleOffer->model?->name,
            'derivative' => $vehicleOffer->derivative,
            'colour' => $vehicleOffer->colour,
            'fuel' => $vehicleOffer->fuelType?->name,
            'transmission' => $vehicleOffer->transmission?->name,
            'body-type' => $vehicleOffer->bodyStyle?->name,
            'drivetrain' => $vehicleOffer->drivetrain?->name,
            'engine_size_cc' => $vehicleOffer->engine_size_cc . ' cc',
            'battery_range' => $vehicleOffer->battery_range,
            'battery_capacity_kwh' => $vehicleOffer->battery_capacity_kwh . ' kwh',
            'battery_usable_capacity_kwh' => $vehicleOffer->battery_usable_capacity_kwh . ' kwh',
            'battery_charge_time' => $vehicleOffer->battery_charge_time,
            'battery_quick_charge_time' => $vehicleOffer->battery_quick_charge_time,
        ];

        $specs += $vehicleOffer
            ->features
            ->pluck('name')
            ->toArray();

        return $specs;
    }
}
