<?php 

namespace App\Services;

use App\Ai\Agents\RedressScotlandEstimator;
use App\Models\Claim\Claim;
use Laravel\Ai\Enums\Lab;
use Illuminate\Support\Facades\Log;
use Throwable;

class RedressEstimateService
{
    public function estimate(Claim $claim): array
    {
        $claim->load([
            'careSettings.institution',
            'impactDetail',
        ]);

        $careSettings = $claim->careSettings
            ->filter(fn ($setting) => filled($setting->statement))
            ->map(fn ($setting) => [
                'care_setting_id' => $setting->id,
                'institution' => $setting->institution?->name,
                'dates' => $setting->dates,
                'people_involved' => $setting->people_involved,
                'statement' => $setting->statement,
            ])
            ->values()
            ->all();

        $impact = $claim->impactDetail;

        $prompt = json_encode([
            'care_settings' => $careSettings,
            'impact_factors' => [
                'has_received_relevant_payment' => (bool) $impact?->has_received_relevant_payment,
                'has_criminal_conviction' => (bool) $impact?->has_criminal_conviction,
                'payment_date' => $impact?->payment_date,
                'paying_organisation' => $impact?->paying_organisation,
                'payment_amount' => $impact?->payment_amount,
            ],
        ], JSON_PRETTY_PRINT);

        try {

            $response = (new RedressScotlandEstimator)->prompt(
                "Estimate the Redress Scotland level and value for this claim:\n\n".$prompt,
                provider: Lab::OpenAI,
                model: 'gpt-5.4',
            );

            $data = $response->toArray();

            $claim->redressEstimate()->updateOrCreate(
                ['claim_id' => $claim->id],
                [
                    'level' => $data['level'],
                    'value_min' => $data['value_min'],
                    'value_max' => $data['value_max'],
                    'confidence' => $data['confidence'],
                    'rationale' => $data['rationale'],
                    'statement_results' => $data['statement_results'],
                    'raw_response' => $data,
                ]
            );

            return $data;

        } catch (Throwable $e) {
            Log::error('Failed to generate Redress estimate.', [
                'claim_id' => $claim->id,
                'client_id' => $claim->client_id,
                'message' => $e->getMessage(),
                'exception' => $e::class,
                'trace' => $e->getTraceAsString(),
            ]);

            throw new \RuntimeException(
                'Unable to generate a provisional value at the moment. Please try again later.'
            );
        }
    }
}