from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
import ollama
from rest_framework import status
import re
import json

class PromptView(APIView):
    def extract_json_from_llm(self, text: str) -> dict:
        # Remove ```json and ```
        cleaned = re.sub(r"```json|```", "", text, flags=re.IGNORECASE).strip()
        return json.loads(cleaned)

    def post(self, request, *args, **kwargs):
        # Access the incoming JSON data as a Python dictionary
        data = request.data
        prompt_data = data.get("prompt", "")
        prompt_str = f"""Role:
        Act as an Expert Technical Recruiter and Data Parsing AI.
        Input Data:
        I will provide you with the raw text from an EMAIL BODY or PDF or Word, which containing an  unstructured Job Description (JD).
        Your Task:
        Analyze: Read the text and identify key job details. Ignore email metadata (signatures, "Sent from my iPhone", greetings, and thread headers).
        Semantic Extraction & Tuning:
        Interpret Meaning: If the email says, "looking for a rockstar in Python," interpret this as "Expert proficiency in Python" under skills.
        Standardize: Expand only universal recruitment abbreviations (e.g., "wfh" -> "Remote"). Strictly preserve Client Acronyms, Project Codes, and Proper Nouns exactly as written (e.g., keep "LTA", "JPMC", "DBS" as is; do not expand them).
        Categorize: Semantically distinguish between what is "Required" (Must have) vs. "Preferred" (Nice to have/Bonus).
        Refine: Clean up the grammar and tone of the extracted text to be professional and suitable for a formal JD.
        Audit Transformation: Track every specific change made, including which input headers were mapped to which output keys.
        Format: Output the data strictly into the specific JSON format defined below.
        Rules for Extraction:
        If a field is not mentioned in the email, return "Not Specified".
        jd_date: Extract the date from the email text if present, otherwise use "Current".
        job_title : Retain the given title in the JD
        ai_title : Tuned and Generated Title from the JD
        job_type: type of Job in the JD example Contract or Employee or etc..
        job_id: reference for the JD or JD identifier
        duration : Duration of the Job requirement in months, if not specified use 24+ months
        about_company: If not explicitly stated, try to infer the company name/domain from the context, or leave as "Not Specified".
        no_of_open_positions: If not explicitly stated, give default value as 1
        primary_skills: highly important skills required for the JD
        secondary_skills: technical skills exclude the primary skills
        domain_requirements: must specified as domain skills in the JD
        Specific Instruction for "changes" field:
        You must generate a semicolon-separated string listing THREE types of changes:
        MAPPING: Which input section was mapped to which JSON key (e.g., "Mapped 'Key Responsibilities' to 'responsibilities'").
        CORRECTION: Content fixes (e.g., "Corrected '58 years' to '5-8 Years'").
        INFERENCE: Data derived from context (e.g., "Inferred 'LTA' is the Domain/Client").
        Output Format:
        Return ONLY a single valid JSON object. Do not include any conversational text.
        ```json
            {{
            "ai_title" : "String",
            "job_title" : "String",
            "job_type" : "String",
            "job_id" : "String",
            "about_company"  : "String",
            "no_of_open_positions" : "String",
            "job_summary"  : "String",
            "responsibilities" : "String",
            "domain_requirements" : "String",
            "certification_requirements" : "String",
            "security_clearance_requirements" : "String",
            "years_of_experience" : "String",
            "duration" : "String",
            "onsite_job" : "String",
            "job_location" : "String",
            "salary_range" : "String",
            "required_qualifications" : "String",
            "preferred_qualifications" : "String",
            "working_hours" : "String",
            "benefits" : "String",
            "requirement_priority" : "String",
            "search_pattern" : {{
                "job_title": "String",
                "location": "String",
                "education": ["String"],
                "primary_skills": ["String"],
                "secondary_skills": ["String"],
                "soft_skills": ["String"],
                "tools_and_frameworks": ["String"],
                "salary_range": "String",
                "keywords": ["String"],
                "domain_requirements": ["String"]
            }},
            "changes": "String",
            }}
            ```
        Input Email Body:
            {{{prompt_data}}}
        """
        print ("data: ", prompt_str)
        prompt_response = ollama.generate(
        model='deepseek-r1:7b',
        prompt=prompt_str, 
        options={'num_thread': 16,  # Match this to your physical CPU cores
        'num_ctx': 4096  # Limit memory usage for faster processing
        }
        )
        
      
        if prompt_response :
            response_data = self.extract_json_from_llm(prompt_response['response'] )
            print(response_data)
            
            # Return a response with the validated data
            return Response(response_data, status=status.HTTP_201_CREATED)
        
        # Return errors if validation fails
        return Response("Error in Prompt response", status=status.HTTP_400_BAD_REQUEST)

