import { readFile } from "node:fs/promises";
import path from "node:path";

export const runtime = "nodejs";

type EvaluationPolicy = {
  policyId: string;
  job_description: string;
  overall_summary: string;
  hard_requirements: string[];
};

type RunEvaluationRequest = {
  policy: EvaluationPolicy;
};

function getOpenAiKey() {
  return process.env.AI_PROVIDER_KEY ?? process.env.AI_PROVIDER_KEY ?? "";
}

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as RunEvaluationRequest;
    if (!body?.policy || typeof body.policy !== "object") {
      return Response.json({ error: "Missing policy in request body." }, { status: 400 });
    }

    const openAiKey = getOpenAiKey();
    if (!openAiKey) {
      return Response.json(
        { error: "OPENAI_API_KEY is not configured on the server." },
        { status: 500 }
      );
    }

    const resumePath = path.join(process.cwd(), "inputs", "resume_foxit_structure.json");
    const resumeJson = await readFile(resumePath, "utf-8");
    const policyJson = JSON.stringify(body.policy, null, 2);

    const systemInstructions =
      "You are an HR Assistant AI. Convert the resume and job description into JSON with keys: " +
      "candidate_name, candidate_phone_number, overall_fit_score (0-100), matching_skills (string[]), " +
      "skill_gaps (string[]), overall_summary (string).\n\n" +
      "Scoring rules:\n" +
      "- Use the provided POLICY JSON strictly, it will include a job_description field.\n" +
      "- Normalize skills to lowercase tokens and dedupe.\n" +
      "- If any hard_requirements are missing, cap overall_fit_score at min(min_score-1, 30).\n" +
      "- Otherwise compute overall_fit_score by summing weights for matched skills, " +
      "scale to 0-100, and round to nearest integer.\n" +
      "- Do not add extra keys. Unknown values must be the string 'Unknown'.";

    const payload = {
      model: "gpt-4o-mini",
      response_format: { type: "json_object" },
      messages: [
        { role: "system", content: systemInstructions },
        {
          role: "user",
          content:
            `POLICY:\n\`\`\`json\n${policyJson}\n\`\`\`\n\n` +
            `RESUME:\n""" ${resumeJson} """\n\n`,
        },
      ],
    };

    const aiResponse = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${openAiKey}`,
      },
      body: JSON.stringify(payload),
    });

    const rawText = await aiResponse.text();
    let aiJson: Record<string, unknown> = {};
    try {
      aiJson = rawText ? (JSON.parse(rawText) as Record<string, unknown>) : {};
    } catch {
      return Response.json(
        {
          error: "OpenAI response was not valid JSON.",
          status: aiResponse.status,
          rawText,
        },
        { status: 502 }
      );
    }

    if (!aiResponse.ok) {
      return Response.json(
        {
          error: "OpenAI API call failed.",
          status: aiResponse.status,
          details: aiJson,
        },
        { status: 502 }
      );
    }

    const content = (aiJson.choices as Array<Record<string, unknown>> | undefined)?.[0]
      ?.message as { content?: string } | undefined;
    const outputText = content?.content ?? "{}";

    let evaluation: Record<string, unknown> = {};
    try {
      evaluation = JSON.parse(outputText) as Record<string, unknown>;
    } catch {
      evaluation = { raw: outputText };
    }

    return Response.json({
      evaluation,
      model: aiJson.model,
      usage: aiJson.usage,
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown server error";
    return Response.json({ error: message }, { status: 500 });
  }
}
