<?php

namespace App\Models;

use CodeIgniter\Model;

class TransportAiSettingsModel extends Model
{
    protected $table         = 'transport_ai_settings';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $updatedField  = 'updated_at';
    protected $createdField  = '';

    protected $allowedFields = [
        'fuel_price_per_litre', 'cost_per_km',
        'consumption_car', 'consumption_van', 'consumption_truck',
        'consumption_bus', 'consumption_motorcycle', 'consumption_other',
        'driver_max_daily_minutes', 'pickup_service_minutes', 'arrival_buffer_minutes',
        'default_base_location_id',
        'road_factor', 'average_speed_kmh', 'osrm_base_url',
        'llm_provider', 'llm_api_base_url', 'llm_api_key', 'llm_model',
        'updated_by',
    ];

    public const LLM_PROVIDERS = ['none', 'openai'];

    public function getSettings(): array
    {
        $row = $this->find(1);
        if (! $row) {
            return [
                'id'                       => 1,
                'fuel_price_per_litre'     => 0.200,
                'cost_per_km'              => 0.050,
                'consumption_car'          => 8.00,
                'consumption_van'          => 12.00,
                'consumption_truck'        => 25.00,
                'consumption_bus'          => 22.00,
                'consumption_motorcycle'   => 4.00,
                'consumption_other'        => 12.00,
                'driver_max_daily_minutes' => 480,
                'pickup_service_minutes'   => 3,
                'arrival_buffer_minutes'   => 15,
                'default_base_location_id' => null,
                'road_factor'              => 1.35,
                'average_speed_kmh'        => 40.00,
                'osrm_base_url'            => 'https://router.project-osrm.org',
                'llm_provider'             => 'none',
                'llm_api_base_url'         => null,
                'llm_api_key'              => null,
                'llm_model'                => null,
            ];
        }

        return $row;
    }

    public function consumptionForType(array $settings, string $vehicleType): float
    {
        $key = 'consumption_' . $vehicleType;

        return (float) ($settings[$key] ?? $settings['consumption_other'] ?? 12.0);
    }
}
