<?php

namespace App\Services\Resume;

use App\Contracts\ResumeAnalyzer;
use App\Services\Settings\SettingsService;
use OpenAI;
use RuntimeException;

class OpenAiResumeAnalyzer implements ResumeAnalyzer
{
    public function __construct(private readonly SettingsService $settings) {}

    /**
     * @return array{
     *     ats_score?: int,
     *     remote_readiness_score?: int,
     *     extracted_skills?: array<int, string>,
     *     role_suggestions?: array<int, string>,
     *     missing_keywords?: array<int, string>,
     *     resume_improvements?: array<int, string>,
     *     summary?: string
     * }
     */
    public function analyze(string $resumeText): array
    {
        if (! $this->settings->isEnabled('openai.enabled')) {
            throw new RuntimeException('OpenAI resume analysis is disabled.');
        }

        $apiKey = (string) $this->settings->get('openai.api_key', config('services.openai.api_key'));

        if (! filled($apiKey)) {
            throw new RuntimeException('OpenAI API key is not configured.');
        }

        $maxResumeLength = (int) $this->settings->get('openai.maximum_resume_text_length', 25000);

        if ($maxResumeLength > 0 && mb_strlen($resumeText) > $maxResumeLength) {
            $resumeText = mb_substr($resumeText, 0, $maxResumeLength);
        }

        $response = OpenAI::client($apiKey)
            ->chat()
            ->create([
                'model' => (string) $this->settings->get('openai.resume_analysis_model', config('services.openai.resume_analysis_model', 'gpt-4.1-mini')),
                'response_format' => ['type' => 'json_object'],
                'temperature' => (float) $this->settings->get('openai.temperature', 0.2),
                'max_tokens' => (int) $this->settings->get('openai.maximum_tokens_per_request', 2000),
                'messages' => [
                    [
                        'role' => 'system',
                        'content' => 'You are an expert ATS and remote-work resume analyst. Return only valid JSON.',
                    ],
                    [
                        'role' => 'user',
                        'content' => $this->prompt($resumeText),
                    ],
                ],
            ]);

        $content = $response->choices[0]->message->content ?? '{}';
        $analysis = json_decode($content, true);

        if (! is_array($analysis)) {
            throw new RuntimeException('OpenAI returned invalid JSON.');
        }

        return $analysis;
    }

    private function prompt(string $resumeText): string
    {
        return <<<'PROMPT'
Analyze this resume for a remote job matching platform.

Return JSON with exactly these keys:
- ats_score: integer 0-100
- remote_readiness_score: integer 0-100
- extracted_skills: array of strings
- role_suggestions: array of strings
- missing_keywords: array of strings
- resume_improvements: array of strings
- summary: short string

Focus on tech, design, marketing, sales, writing, support, product, operations, virtual assistant, finance, HR, data, AI, and general remote jobs when suggesting roles.

Resume text:
PROMPT."\n\n".$resumeText;
    }
}
