import re
import pandas as pd
import math
from AgentProxy import AgentProxy 

def is_none_or_nan(variable):
    return variable is None or (isinstance(variable, (int, float)) and math.isnan(variable))

result_category_list = [
    "完成需求确认与收集",
    "完成技术评估与测试",
    "完成商务谈判与合同准备",
    "完成内部审批与预算确认",
    "完成项目立项与采购流程",
    "完成关系建立与维护",
    "完成市场调研与竞争分析",
    "完成产品推广与市场活动",
    "完成技术支持与售后服务",
    "完成续约与增购谈判"
]


df = pd.read_excel('analysis_result_action_result_top200.xlsx')
data = []

for index, row in df.iterrows():
    text = row["行动结果"]
    if is_none_or_nan(text):
        print(f"index{index} ")
        continue

    action_pattern = re.compile(r'\*\*销售动作\*\*：(.+?)\n')
    category_pattern = re.compile(r'\*\*销售动作归类\*\*：(.+?)\n')
    result_pattern = re.compile(r'\*\*销售动作行动结果\*\*：(.+?)\n')
    abstract_result_pattern = re.compile(r'\*\*抽象销售动作行动结果\*\*：(.+?)\n')
    # Find all matches
    actions = action_pattern.findall(text)
    categories = category_pattern.findall(text)
    results = result_pattern.findall(text)
    abstract_results = abstract_result_pattern.findall(text)
    if (len(actions) == len(categories) and len(actions) == len(results) and len(actions) == len(abstract_results)):
        print(f"index{index} result compliance: true")
    else:
        print(f"index{index} result compliance: false")
        continue  

    # Combine into a list of dictionaries
    for action, category, result, abstract_result in zip(actions, categories, results, abstract_results):
        data.append({
            "action": action,
            "action_category": category,
            "result": result,
            "result_category": abstract_result
        })

result_list = []
for item in data:
    print(item["result"])
    result_list.append(item["result"])

# prompt_abstract_result = (f"以下列表为销售动作行动结果，请分析各个结果，将其抽象、总结成通用、概括性的销售行动结果，请注意要体现出结果，比如确定了需求，达成了签约，即完成了什么任务达成了什么效果"
#                           f"{','.join(result_list)}")

api_key = '25bda2c39c0f8ca0' 
api_secret = 'e0008b9b9727cb8ceea5a132dbe62495' 
assistant_id = "66bb09a84673b57506fe7bbd" 
agent = AgentProxy(assistant_id, api_key, api_secret)

# res = agent.send_message(prompt_abstract_result)
# print(res)


statistics = {}
for index, row in df.iterrows():
    try:
        text = row["当前详细状态及Close节奏"]
        stage = row["Sales stage"]
        if stage not in statistics:
            statistics[stage] = 0
        statistics[stage] += 1
        prompt_result_analysis = (f"以下是销售行动结果列表:"
                                  f"{','.join(result_category_list)}"
                                  f"请分析如下销售日志，提取出其中的销售动作，并且分析该销售动作是否达成了上述定义的销售动作结果之一，如达成，请将该销售动作映射到行动结果上，如果未达成，则映射到\"未达成\"上"
                                  f"销售日志如下：{text}"
                                  f"输出格式如下："
                                  f"**销售动作**:"
                                  f"**销售动作行动结果**:"
                                  )
        print(prompt_result_analysis)
        res = agent.send_message(prompt_result_analysis)
        df.at[index, "销售动作行动结果"] = res
        print(res)
    except Exception as e:
        print(f"Error processing row {index}: {e}")
        df.at[index, "销售动作行动结果"] = f"Error: {e}"
df.to_excel('analysis_result_action_result_stage2.xlsx')