<?php

namespace Modules\Vrc\Services\Ai;

use Modules\Vrc\Entities\VrcService;
use Modules\Vrc\Entities\VrcVehicle;

/**
 * AI estimate assistant (spec R3.3): turns a customer symptom into suggested
 * repair services + likely causes + labor hours, grounded in the workshop's
 * own VRC service catalog and the vehicle. Reuses the AiCore engine as a SOFT
 * dependency — returns a clear "not configured" result if AiCore is absent or
 * the business has no AI provider set up. The model is told to only use
 * services from the provided context (no invented work).
 */
class VrcEstimateAssistant
{
    public function available(): bool
    {
        return class_exists(\Modules\AiCore\Entities\AiProvider::class)
            && class_exists(\Modules\AiCore\Entities\Services\AiClient::class);
    }

    /**
     * @return array{ok:bool, text?:string, error?:string}
     */
    public function suggest(int $businessId, string $symptom, ?VrcVehicle $vehicle = null): array
    {
        $symptom = trim($symptom);
        if ($symptom === '') {
            return ['ok' => false, 'error' => __('vrc::lang.ai_need_symptom')];
        }
        if (! $this->available()) {
            return ['ok' => false, 'error' => __('vrc::lang.ai_unavailable')];
        }

        try {
            $settings = \Modules\AiCore\Entities\AiProvider::forBusiness($businessId);
            if (! $settings->isConfigured()) {
                return ['ok' => false, 'error' => __('vrc::lang.ai_not_configured')];
            }

            $system = \Modules\AiCore\Entities\Services\PromptBuilder::system($settings, [
                'extra' => 'You are an automotive service advisor. From the customer symptom, give: '
                    . '(1) the most likely causes, (2) recommended services CHOSEN ONLY from the service list '
                    . 'in the context, and (3) a rough labor-hours estimate. Be concise and conservative. '
                    . 'Never invent services that are not listed.',
            ]);

            $user = \Modules\AiCore\Entities\Services\PromptBuilder::userEnvelope(
                'Customer symptom: ' . $symptom,
                $this->context($businessId, $vehicle)
            );

            $result = (new \Modules\AiCore\Entities\Services\AiClient())->chat($settings, $system, $user, [
                'module'  => 'vrc',
                'feature' => 'estimate_assistant',
            ]);

            if (empty($result['ok'])) {
                return ['ok' => false, 'error' => $result['error'] ?? __('vrc::lang.ai_failed')];
            }

            return ['ok' => true, 'text' => (string) $result['text']];
        } catch (\Throwable $e) {
            return ['ok' => false, 'error' => __('vrc::lang.ai_failed')];
        }
    }

    /** Grounding context: the workshop's services + the vehicle. */
    protected function context(int $businessId, ?VrcVehicle $vehicle): string
    {
        $lines = [];
        if ($vehicle) {
            $lines[] = 'Vehicle: ' . trim((optional($vehicle->make)->name ?? '') . ' ' . (optional($vehicle->model)->name ?? '')) . ' ' . ($vehicle->year ?: '');
            if ($vehicle->odometer) {
                $lines[] = 'Odometer: ' . $vehicle->odometer . ' ' . $vehicle->odometer_unit;
            }
        }

        $lines[] = "\nAvailable repair services (name — default labor hours — price):";
        $services = VrcService::where('business_id', $businessId)->where('is_active', true)
            ->orderBy('name')->limit(80)->get(['name', 'default_labor_hours', 'default_price']);
        foreach ($services as $s) {
            $lines[] = "- {$s->name} — {$s->default_labor_hours}h — {$s->default_price}";
        }

        return implode("\n", $lines);
    }
}
