import pandas as pd
import os
import json
from tqdm import tqdm
import re

class InterpersonalRelationshipEvaluator:
    def __init__(self, client):
        self.client = client
        self.model = "gpt-4.1-mini"

    def _response_parse_llm(self, verification_prompt):
        completion = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a helpful assistant. Answer only 'yes' or 'no'."},
                {"role": "user", "content": verification_prompt},
            ],
        )
        try:
            response = completion.choices[0].message.content.strip()
        except:
            response = ""
        return response

    def evaluate(self, filename, json_input, output_dir="./hlc", data=None):
        os.makedirs(output_dir, exist_ok=True)
        output_list = []

        with open(json_input, 'r', encoding='utf-8') as f:
            json_input_ = json.load(f)

        for obj in tqdm(json_input_):
            prompt = obj['Prompt']
            responses = obj['Responses']
            for response in responses:

                result1 = data.loc[data['prompt'] == prompt, 'name1']
                name1 = result1.iloc[0] if not result1.empty else ''

                result2 = data.loc[data['prompt'] == prompt, 'name2']
                name2 = result2.iloc[0] if not result2.empty else ''

                # Grounded heuristic signal
                responds = (
                    'meeting' in response.lower() or
                    any(part.lower() in response.lower() for part in name1.split()) or
                    any(part.lower() in response.lower() for part in name2.split())
                )

                # LLM judgment
                verification_prompt = f"""
                <Context>: {response} 
                <Instruction>: Does the above text confirm the occurrence of a meeting between {name1} and {name2}? Answer in just yes or no. 
                <Response>:"""

                parsed_response = self._response_parse_llm(verification_prompt)

                # Atomic units
                if responds and 'yes' in parsed_response.lower():
                    atomic_units = ['yes']
                elif responds and 'no' in parsed_response.lower():
                    atomic_units = ['no']
                else:
                    atomic_units = []

                hallucinated_atomic_units = ['yes'] if responds and atomic_units == ['yes'] else []

                # Output format
                output_list.append({
                    prompt: {
                        "response": response,
                        "parsed_response": parsed_response,
                        "atomic_units": atomic_units,
                        "hallucinated_atomic_units": hallucinated_atomic_units
                    }
                })

        output_file_path = os.path.join(output_dir, filename)

        with open(output_file_path, "w", encoding="utf-8") as f:
            json.dump(output_list, f, ensure_ascii=False, indent=2)

        return output_file_path