<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Resume;
use App\Models\AtsReport;
use App\Services\LLMService;

class ATSController extends Controller
{
   public function form(Resume $resume)
    {
        $reports = $resume->atsReports()->latest()->get();
        return view('resumes.ats', compact('resume', 'reports'));
    }

    
       public function analyze(Request $request, Resume $resume)
{
    $request->validate([
        'job_description' => 'required|string|min:50',
        'model' => 'nullable|in:openai,gemini',
    ]);

    $provider = $request->input('model', 'openai');

    // Build resume text
    $resumeText = "
    Name: {$resume->first_name} {$resume->last_name}
    Title: {$resume->job_title}
    Summary: {$resume->summary}
    Skills: " . $resume->skills->pluck('skill_name')->implode(', ') . "
    Experience: " . $resume->experiences->pluck('position')->implode(', ') . "
    ";

    // ✅ Strict prompt for consistent JSON
    $prompt = <<<PROMPT
You are an AI ATS (Applicant Tracking System) evaluator.

Evaluate how well the following resume matches the job description.
Give a numeric score (0–100), and list missing keywords and actionable improvement suggestions.

Output ONLY valid JSON (no explanations, no markdown), exactly in this format:

{
  "score": <number>,
  "missing_keywords": ["keyword1", "keyword2"],
  "suggestions": ["suggestion1", "suggestion2"]
}

RESUME:
{$resumeText}

JOB DESCRIPTION:
{$request->job_description}
PROMPT;

    $response = \App\Services\LLMService::analyze($prompt, $provider);
    $content = $response['choices'][0]['message']['content'] ?? '{}';

    // ✅ Try to extract JSON even if AI wraps text around it
    if (!($decoded = json_decode($content, true))) {
        if (preg_match('/\{.*\}/s', $content, $match)) {
            $decoded = json_decode($match[0], true);
        }
    }

    // ✅ Fallback defaults
    $score = $decoded['score'] ?? 0;
    $missing = $decoded['missing_keywords'] ?? [];
    $suggestions = $decoded['suggestions'] ?? [];

    // Save ATS report
    \App\Models\AtsReport::create([
        'resume_id' => $resume->id,
        'job_description' => $request->job_description,
        'score' => $score,
        'missing_keywords' => $missing,
        'suggestions' => $suggestions,
    ]);

    return redirect()->route('ats.form', $resume->id)
        ->with('success', "ATS analysis completed via {$provider}!")
        ->with('score', $score);
}
    }

