I am building an application in Next.js, TailwindCSS, Appwrite, and Zustand. So now I want you make this api generate output according to the data object I have provided"

EXAMPLE DATAOBJ
"resume":{"title":"Aditya Mallah","summary":"Results-driven Marketing Specialist with a proven track record of driving sales growth and developing client relationships in the tech industry. Skilled in market research, lead generation, and solution articulation. Proficient in Google Digital Marketing and E-commerce, Google Advanced Data Analytics, and HubSpot Inbound Marketing Certification.","email":"mallahadityawork@gmail.com","phone":"+15197212456","location":"Waterloo, Ontario","sections":{"socialLinks":[{"platform":"LinkedIn","url":<PRESIDIO_ANONYMIZED_URL>,"id":"adityamallah"}],"education":[{"school":"Conestoga","degree":"Post Graduate","fieldOfStudy":"Marketing Communications","startDate":"","endDate":"","description":"","id":"conestoga"},{"school":"Mumbai University","degree":"Bachelor’s","fieldOfStudy":"Mass Media (Advertising)","startDate":"","endDate":"","description":"","id":"mumbai-university"}],"experience":[{"jobTitle":"Demand Generation Manager","companyName":"Fintech ","location":"Waterloo","startDate":"2024-01-12","endDate":"2024-03-29","description":"Developed and executed comprehensive marketing strategies for B2B clients, resulting in an average 35% increase in lead generation. Managed end-to-end PPC campaigns with budgets ranging from CAD 10,000 to CAD 50,000, achieving a 20% reduction in cost per acquisition. Created compelling marketing content, including whitepapers and case studies, increasing client engagement by 40%.","id":"demand-generation-manager"},{"jobTitle":"Digital Marketing Specialist","companyName":"Rocksolar","location":"Waterloo","startDate":"2023-01-09","endDate":"2024-04-30","description":"Conducted in-depth market research and built targeted prospect lists aligning with the Ideal Customer Profile (ICP). Generated leads and built relationships with IT and business leaders through high-level qualifying conversations. Utilized Google Digital Marketing and E-commerce skills to articulate the value of RockSolar's solutions and managed services to prospective clients.","id":"digital-marketing-specialist"}],"skills":[{"name":"Market Research","proficiencyLevel":"Advanced","id":"market-research"},{"name":"Lead Generation","proficiencyLevel":"Advanced","id":"lead-generation"},{"name":"Solution Articulation","proficiencyLevel":"Advanced","id":"solution-articulation"},{"name":"Google Digital Marketing and E-commerce","proficiencyLevel":"Advanced","id":"google-digital-marketing-and-e-commerce"},{"name":"Google Advanced Data Analytics","proficiencyLevel":"Advanced","id":"google-advanced-data-analytics"},{"name":"HubSpot Inbound Marketing Certification","proficiencyLevel":"Advanced","id":"hubspot-inbound-marketing-certification"},{"name":"English","proficiencyLevel":"Native","id":"english"},{"name":"French","proficiencyLevel":"Basic","id":"french"}],"certifications":[{"name":"Google Digital Marketing and E-commerce","issuingOrganization":"Google ","issueDate":"","expirationDate":"","description":"","id":"google-digital-marketing-and-e-commerce-certification"},{"name":"Google Advanced Data Analytics","issuingOrganization":"Google","issueDate":"","expirationDate":"","description":"","id":"google-advanced-data-analytics-certification"},{"name":"HubSpot Inbound Marketing Certification","issuingOrganization":"HubSpot","issueDate":"","expirationDate":"","description":"","id":"hubspot-inbound-marketing-certification"}],"projects":[{"name":"Growth Gradient","description":"Developed and executed comprehensive marketing strategies for B2B clients, resulting in an average 35% increase in lead generation. Managed end-to-end PPC campaigns with budgets ranging from CAD 10,000 to CAD 50,000, achieving a 20% reduction in cost per acquisition. Created compelling marketing content, including whitepapers and case studies, increasing client engagement by 40%.","technologiesUsed":"","link":"","startDate":"","endDate":"","id":"growth-gradient"}],"languages":[{"name":"English","proficiencyLevel":"Native","id":"english"},{"name":"French","proficiencyLevel":"Basic","id":"french"}],"awards":[]}}


API
import { NextResponse } from "next/server";
import Together from "together-ai";

const together = new Together({ apiKey: process.env.TOGETHER_API_KEY });

export async function POST(request) {
  try {
    const { action, ...data } = await request.json();

    switch (action) {
      case "regenerate":
        return await handleRegenerate(data);
      case "chat":
        return await handleChat(data);
      default:
        return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    }
  } catch (error) {
    console.error("Error in API:", error);
    return NextResponse.json(
      { error: error.message || "Internal server error" },
      { status: 500 }
    );
  }
}

async function handleRegenerate({
  selectedSections,
  profile,
  jobDescription,
  currentResume,
  message,
  originalSections,
}) {
  if (
    !selectedSections ||
    !profile ||
    !jobDescription ||
    !currentResume ||
    !originalSections ||
    !message
  ) {
    return NextResponse.json(
      { error: "Missing required fields" },
      { status: 400 }
    );
  }

  const prompt = generateRegenerationPrompt(
    selectedSections,
    profile,
    jobDescription,
    currentResume,
    message,
    originalSections
  );

  const response = await together.chat.completions.create({
    messages: [{ role: "user", content: prompt }],
    model: "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
    max_tokens: 2048,
    temperature: 0.7,
    top_p: 0.9,
    n: 1,
    stop: ["
", "
"],
  });

  const generatedContent = response.choices[0].message.content.trim();
  const jsonString = extractJson(generatedContent);

  try {
    const jsonContent = JSON.parse(jsonString);
    const validatedContent = validateResumeContent(jsonContent);

    const replyPrompt = generateReplyPrompt(
      selectedSections,
      originalSections,
      validatedContent,
      message
    );

    const replyResponse = await together.chat.completions.create({
      messages: [{ role: "user", content: replyPrompt }],
      model: "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
      max_tokens: 1024,
      temperature: 0.7,
      top_p: 0.9,
      n: 1,
      stop: ["
", "
"],
    });

    const reply = replyResponse.choices[0].message.content.trim();

    return NextResponse.json({ result: validatedContent, reply });
  } catch (parseError) {
    console.error("Error parsing generated content:", parseError);
    return NextResponse.json(
      { error: "Generated content is not valid JSON", generatedContent },
      { status: 500 }
    );
  }
}

async function handleChat({ message, chatHistory, resume, jobDescription }) {
  if (!message || !chatHistory || !resume || !jobDescription) {
    return NextResponse.json(
      { error: "Missing required fields" },
      { status: 400 }
    );
  }

  const formattedHistory = chatHistory.map((msg) => ({
    role: msg.type === "user" ? "user" : "assistant",
    content: msg.content,
  }));

  const systemMessage = `
    You are a helpful assistant for resume and job application related queries.
    You have access to the following information:
    Resume: ${JSON.stringify(resume, null, 2)}
    Job Description: ${jobDescription}
    Please use this information to provide accurate and tailored responses to the user's questions about their resume and job application.
  `;

  const response = await together.chat.completions.create({
    messages: [
      { role: "system", content: systemMessage },
      ...formattedHistory,
      { role: "user", content: message },
    ],
    model: "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
    max_tokens: 1024,
    temperature: 0.7,
    top_p: 0.9,
    n: 1,
    stop: ["
", "
"],
  });

  const reply = response.choices[0].message.content.trim();

  return NextResponse.json({ reply });
}

const sectionPrompts = {
  summary:
    "Update the summary to highlight key achievements and skills relevant to the job description.",
  experience:
    "Enhance the experience section to emphasize relevant responsibilities and accomplishments.",
  skills:
    "Modify the skills section to showcase skills that align closely with the job requirements.",
  education:
    "Adjust the education section to highlight relevant courses or honors.",
};

function generateRegenerationPrompt(
  selectedSections,
  profile,
  jobDescription,
  currentResume,
  message,
  originalSections
) {
  const sectionInstructions = selectedSections
    .map((section) => {
      const instruction = sectionPrompts[section] || "";
      return `Section: ${section}\nInstruction: ${instruction}\nOriginal Content: ${JSON.stringify(originalSections[section], null, 2)}`;
    })
    .join("\n\n");

  return `
    You are a resume writing assistant. Please regenerate the following sections of the resume based on the profile, job description, and current resume. Only modify the selected sections:

    Selected Sections: ${selectedSections.join(", ")}
    Profile: ${JSON.stringify(profile, null, 2)}
    Job Description: ${jobDescription}
    Current Resume: ${JSON.stringify(currentResume, null, 2)}
    User Message: ${message}
    Instructions:
    For each of the selected sections, follow these specific instructions:
    ${sectionInstructions}

    General Instructions:
    - Only modify the sections specified in the Selected Sections.
    - Maintain the same structure and format as the current resume.
    - Tailor the content to better match the job description and highlight relevant skills and experiences.
    - Ensure that the regenerated sections seamlessly integrate with the rest of the resume.
    - Consider the user's message when making changes: "${message}"
    - Improve the content more than the original, addressing the user's request.
    - Return the entire resume JSON object, including both modified and unmodified sections.

    Return only the JSON object, no additional text.
  `;
}

function generateReplyPrompt(
  selectedSections,
  originalSections,
  validatedContent,
  userMessage
) {
  const regeneratedSections = selectedSections.reduce((acc, section) => {
    acc[section] = validatedContent.sections[section];
    return acc;
  }, {});

  return `
    You have just regenerated the following sections of a resume: ${selectedSections.join(", ")}.
    Here are the original sections: ${JSON.stringify(originalSections, null, 2)}
    And here are the regenerated sections: ${JSON.stringify(regeneratedSections, null, 2)}
    Provide a brief summary of the changes made and any suggestions for further improvements.
    Address the user's request to "${userMessage}".
  `;
}

function extractJson(text) {
  const jsonStart = text.indexOf("{");
  const jsonEnd = text.lastIndexOf("}");
  if (jsonStart !== -1 && jsonEnd !== -1) {
    return text.substring(jsonStart, jsonEnd + 1);
  }
  throw new Error("JSON data not found in the generated content");
}

function validateResumeContent(content) {
  const requiredFields = [
    "title",
    "summary",
    "email",
    "phone",
    "location",
    "sections",
  ];
  const requiredSections = [
    "socialLinks",
    "education",
    "experience",
    "skills",
    "certifications",
    "projects",
    "languages",
    "awards",
  ];

  requiredFields.forEach((field) => {
    if (!content[field]) {
      content[field] = "";
    }
  });

  if (!content.sections || typeof content.sections !== "object") {
    content.sections = {};
  }

  requiredSections.forEach((section) => {
    if (!content.sections[section] || !Array.isArray(content.sections[section])) {
      content.sections[section] = [];
    }
  });

  requiredSections.forEach((section) => {
    content.sections[section] = content.sections[section].map((item) => {
      const validatedItem = { ...item, id: item.id || generateUniqueId() };
      ["startDate", "endDate", "issueDate", "expirationDate", "dateReceived"].forEach((dateField) => {
        if (validatedItem[dateField]) {
          validatedItem[dateField] = validateDate(validatedItem[dateField]);
        }
      });
      return validatedItem;
    });
  });

  return content;
}

function validateDate(dateString) {
  if (!dateString || dateString.trim() === "") return "";

  const date = new Date(dateString);
  if (isNaN(date.getTime())) return "";

  return date.toISOString().split("T")[0];
}

function generateUniqueId() {
  return Math.random().toString(36).substr(2, 9);
}
// function generateUniqueId() {
//     return Date.now().toString() + Math.random().toString(36).substr(2, 9);
// }