import requests

def compute_llm_score_and_feedback(rag_demos, observation, skill_code, instruction, object_list, threshold=-1.0):
    primary_prompt = ""
    primary_prompt += f"Instruction:\n{instruction}\n\n"
    for i, demo in enumerate(rag_demos):
        primary_prompt += f"Demo {i+1}:\n{demo}\n\n"
    primary_prompt += f"Observation:\n{observation}\n\n"
    primary_prompt += f"Skill Code:\n{skill_code}\n\n"
    primary_prompt += f"Object_list:\n{object_list}\n\n"

    url_none_sysp = "http://localhost:8000/v1/completions"
    url_sysp = "http://localhost:8000/v1/chat/completions"
    headers = {"Content-Type": "application/json"}
    
    payload = {
        "model": "meta-llama/Llama-3.1-8B-Instruct",
        "prompt": primary_prompt,
        "max_tokens": 0,
        "temperature": 0.0,
        "logprobs": 5,
        "echo": True
    }
    
    response = requests.post(url_none_sysp, headers=headers, json=payload)
    if response.status_code != 200:
        print("CSC Request failed for LLM Score:", response.status_code, response.text)
        return None, None
    
    result = response.json()
    choice = result["choices"][0]
    
    if "logprobs" in choice and "token_logprobs" in choice["logprobs"]:
        token_logprobs = choice["logprobs"]["token_logprobs"]
        valid_logprobs = [lp for lp in token_logprobs if lp is not None]
        if len(valid_logprobs) > 0:
            llm_score = sum(valid_logprobs) / len(valid_logprobs)
        else:
            llm_score = None
    else:
        llm_score = None

    feedback = ""
    if llm_score is not None and llm_score < threshold:
        feedback_prompt = (
            "Below is the entire context, followed by the LLM Score.\n\n"
            "=== Demos ===\n"
        )
        for i, demo in enumerate(rag_demos):
            feedback_prompt += f"Demo {i+1}:\n{demo}\n\n"
        
        feedback_prompt += (
            "=== Observation ===\n"
            f"{observation}\n\n"
            "=== Skill Code ===\n"
            f"{skill_code}\n\n"
            f"=== LLM Score ===\n"
            f"The current LLM Score is {llm_score}, which is below the threshold of {threshold}.\n\n"
            "=== Instruction ===\n"
            f"{instruction}\n\n"
            "=== Object_list ===\n"
            f"{object_list}\n\n"
            "=== Task ===\n"
            "Please provide feedback on how to improve the skill code. Focus on any potential issues, mistakes, "
            "or improvements, especially regarding force calibration, safety, or logic."
            "Example) An object declared in the code is not in the actual object list.\n\n"
            "=== Format ===\n"
            "Please structure your feedback in the following format:\n"
            "1. **Problem Identification**\n"
            "2. **Justification** (Why is it a problem?)\n"
            "3. **Proposed Solutions** (High-level ideas)\n"
            "4. **Additional Notes** (Anything else that might be helpful)\n\n"
            "Make sure you address how the code can be improved step by step.\n"
        )

        feedback_payload = {
            "model": "meta-llama/Llama-3.2-3B-Instruct",
            "messages": [
                {
                    "role": "system",
                    "content": "Please provide feedback on how to improve the skill code."
                },
                {
                    "role": "user",
                    "content": feedback_prompt
                }
            ],
            "max_tokens": 700,
            "temperature": 0.7,
            "stop": []
        }

        feedback_response = requests.post(url_sysp, headers=headers, json=feedback_payload)
        if feedback_response.status_code == 200:
            feedback_result = feedback_response.json()
            if "choices" in feedback_result and len(feedback_result["choices"]) > 0:
                feedback = feedback_result["choices"][0]["message"].get("content", "").strip()
            else:
                feedback = ""
        else:
            feedback = ""

    return llm_score, feedback
