"use server";

import { prisma } from "@/lib/prisma";
import { GoogleGenerativeAI } from "@google/generative-ai";
import { getCurrentUser } from "@/lib/auth";
import { revalidatePath } from "next/cache";

const API_KEY = process.env.GEMINI_API_KEY || "";
const genAI = new GoogleGenerativeAI(API_KEY);

export async function generateCandidateAIScore(applicationId: string) {
    try {
        const user = await getCurrentUser();
        if (!user || user.role !== "employer") {
            return { success: false, error: "Unauthorized" };
        }

        const application = await prisma.application.findUnique({
            where: { id: applicationId },
            include: {
                job: {
                    include: { skills: { include: { skill: true } } }
                },
                candidate: {
                    include: {
                        profile: true,
                        skills: { include: { skill: true } },
                        experiences: true,
                        education: true
                    }
                }
            }
        });

        if (!application) {
            return { success: false, error: "Application not found or access denied" };
        }
        const app = application as any;
        if (app.job?.employer_id !== user.id) {
            return { success: false, error: "Access denied" };
        }

        const job = app.job as any;
        const candidate = app.candidate as any;

        // Prepare prompt data
        const jobTitle = job.title;
        const jobDesc = job.description;
        const jobSkills = job.skills.map((s: any) => s.skill.name).join(", ");
        const jobRequirements = job.requirements ? (job.requirements as string[]).join("\n- ") : "";

        const candidateHeadline = candidate.profile?.headline || "";
        const candidateBio = candidate.profile?.bio || "";
        const candidateSkills = candidate.skills.map((s: any) => s.skill.name).join(", ");
        const candidateExp = candidate.experiences.map((e: any) => `Title: ${e.title} at ${e.company}\nDescription: ${e.description}`).join("\n\n");

        if (!API_KEY) {
            // Fallback mock scoring if no API key
            const mockScore = Math.floor(Math.random() * 30) + 60; // 60-90
            await saveScore(applicationId, {
                overall_score: mockScore,
                skills_match: mockScore - 5,
                experience_match: mockScore + 5,
                culture_fit: 80,
                ai_summary: "AI API Key missing. Mock evaluation: The candidate has a reasonable profile but requires a manual technical review."
            });
            return { success: true, message: "Generated mock score (API key missing)" };
        }

        const prompt = `
You are an expert ATS (Applicant Tracking System) AI assistant. Evaluate the following candidate against the job description.
Return ONLY a valid JSON object with no markdown formatting or code blocks. Do not include \`\`\`json.

Job Title: ${jobTitle}
Required Skills: ${jobSkills}
Job Description/Requirements:
${jobDesc}
- ${jobRequirements}

---
Candidate Headline: ${candidateHeadline}
Candidate Bio: ${candidateBio}
Candidate Skills: ${candidateSkills}

Candidate Experience:
${candidateExp}

You must respond with the following JSON structure exactly:
{
  "overall_score": <number 0-100 representing overall fit>,
  "skills_match": <number 0-100 indicating how well skills align>,
  "experience_match": <number 0-100 indicating relevance of past experience>,
  "culture_fit": <number 0-100 estimating soft skills/alignment from bio>,
  "ai_summary": "<a 2-3 sentence summary explaining the score, strengths, and weaknesses>"
}`;

        const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });
        const result = await model.generateContent(prompt);
        let text = result.response.text();

        // Clean up markdown if any
        text = text.replace(/```json/g, "").replace(/```/g, "").trim();

        const parsed = JSON.parse(text);

        const scoreData = {
            overall_score: parsed.overall_score || 50,
            skills_match: parsed.skills_match || 50,
            experience_match: parsed.experience_match || 50,
            culture_fit: parsed.culture_fit || 50,
            ai_summary: parsed.ai_summary || "No summary provided."
        };

        await saveScore(applicationId, scoreData);

        return { success: true, score: scoreData };

    } catch (error) {
        console.error("AI Scoring failed:", error);
        return { success: false, error: "Failed to generate AI score." };
    }
}

async function saveScore(applicationId: string, data: any) {
    // Upsert CandidateScore
    await prisma.candidateScore.upsert({
        where: { application_id: applicationId },
        update: data,
        create: {
            application_id: applicationId,
            ...data
        }
    });

    // Mirror overall score to Application.match_score for quick querying
    await prisma.application.update({
        where: { id: applicationId },
        data: { match_score: data.overall_score }
    });

    revalidatePath(`/dashboard/applications/${applicationId}`);
}
