import json
from config import simplemodel
from template import xuanxiang
with open('zhaoping_rule', 'r') as f:
    content = f.read()
import json
obj=json.loads(content)
with open('name_label', 'r') as f:
    content = f.read()
import json
name_label=json.loads(content)
baohuceng = ['10-74', '10-75', '10-77', '10-78', '10-80', '10-81', '10-83', '10-84', '10-86', '10-87', '10-90']
from fallback import fallback
def shuangceng(data,aiclient,sfclient):
    
    completion = aiclient.chat.completions.create(
        model='glm-4.5-air',
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": " 在屋面卷材施工中，卷材可做一层（一道），可做两层（两道）。给你一段文字如下， " + data['tz'] + ",其中提及卷材施工，请问其中明确提及做两层（两道）吗？请回答是或者否"},                       
        ],
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    if len(json_string) < 4:
        if '否' in json_string:
            return False
        return True
    
    completion = sfclient.chat.completions.create(
        model=simplemodel(),
        messages=[
            {"role": "system", "content": "You are a helpful assistant.请将最终答案以JSON格式输出"},
            {"role": "user", "content": " 给你一段文字如下， " + json_string + ",其中给出了一个是否施工两层卷材的判断，请将该判断输出，请输出是或者否"},                       
        ],
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    if '否' in json_string:
        return False
    return True
def zhaopingceng(data,aiclient,sfclient):
    
    completion = aiclient.chat.completions.create(
        model='glm-4.5-air',
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": " 在屋面防水施工中，细石混凝土可能做找平（找坡）层，也可能做面层（保护层）。给你一段文字如下， " + data['tz'] + ",其中提及细石混凝土，请问其中提及细石混凝土是做找平（找坡）层吗？请回答是或者否"},                       
        ],
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    if len(json_string) < 4:
        if '否' in json_string:
            return False
        return True
    
    completion = sfclient.chat.completions.create(
        model=simplemodel(),
        messages=[
            {"role": "system", "content": "You are a helpful assistant.请将最终答案以JSON格式输出"},
            {"role": "user", "content": " 给你一段文字如下， " + json_string + ",其中给出了一个是否为细石混凝土找平层的判断，请将该判断输出，请输出是或者否"},                       
        ],
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    if '否' in json_string:
        return False
    return True
def aifilter3(A, #options
       B, #data
       aiclient,
             qwclient,
             sfclient,
             dw):
    options=[]
    letters = "ABCDEFGHIJK"
    for i in range(len(baohuceng)):
        options.append("给定选项" + letters[i]+"，内容为"+name_label[baohuceng[i]] )

    completion = aiclient.chat.completions.create(
        model="glm-4.5-flash",
        #model="Qwen/Qwen3-14B",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": " 重要提示：匹配保护层做法时，优先考虑材料的匹配性，比如，特征中描述是水泥砂浆，则优先选择水泥砂浆选项而不是防水砂浆选项"},
            {"role": "user", "content": "问题描述： 给定一段工作内容: " + B['label'] + " " +  B['mc'] + " " + B['tz'] +  "，其中包含了屋面保护层的做法。".join(options) + "。请根据工作内容中保护层的描述，选择最匹配的选项并返回结果。例如，如果C选项最匹配，请返回C"},
        ],
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    completion = sfclient.chat.completions.create(
        model=simplemodel(),
        messages=[
            {"role": "system", "content": "You are a helpful assistant.请将最终答案以JSON格式输出"},
            {"role": "user", "content": " 给你一段文字如下， " + json_string + ",其中给出了一个类似于A或者B的选项作为结果，请将该最终结果输出"},                       
        ],
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    answer=[]
    if 'A' in json_string:
        answer.append(name_label[baohuceng[0]])
    if 'B' in json_string:
        answer.append(name_label[baohuceng[1]])
    if 'C' in json_string:
        answer.append(name_label[baohuceng[2]])
    if 'D' in json_string:
        answer.append(name_label[baohuceng[3]])
    if 'E' in json_string:
        answer.append(name_label[baohuceng[4]])
    if 'F' in json_string:
        answer.append(name_label[baohuceng[5]])
    if 'G' in json_string:
        answer.append(name_label[baohuceng[6]])
    if 'H' in json_string:
        answer.append(name_label[baohuceng[7]])
    if 'I' in json_string:
        answer.append(name_label[baohuceng[8]])
    if 'J' in json_string:
        answer.append(name_label[baohuceng[9]])
    if 'K' in json_string:
        answer.append(name_label[baohuceng[10]])
    return answer
def aifilter4(A, #options
       B, #data
       aiclient,
             qwclient,
             sfclient,
             dw):
    options=[]
    letters = "ABCDEFGHIJKLMN"
    for i in range(len(A)):
        options.append("给定选项" + letters[i]+"，内容为"+A[i] )

    completion = aiclient.chat.completions.create(
        model="glm-4.5-air",
        #model="Qwen/Qwen3-14B",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": " 背景知识：石油沥青，沥青马蹄脂，渗透结晶防水材料等都是防水涂料。砂浆隔离层、混凝土防水层不是防水涂料"},
            {"role": "user", "content": " 特殊处理要求：如果选项中有多个防水涂料的选项（砂浆隔离层、混凝土防水层不是防水涂料），则只能选择一个防水涂料选项，且优先选择渗透结晶防水材料；与防水涂料无关的选项全部保留"},
            {"role": "user", "content": " 重要提示：选项指的是给定的A、B、C之类的选项，不是指的工作内容中的可能的1、2、3这样罗列的特征"},
            {"role": "user", "content": " 重要提示：除特殊处理要求提及的内容外，不需考虑选项内容与工作内容是否符合，只需要根据特殊处理要求做出处理"},
            {"role": "user", "content": "问题描述： 给定一段工作内容: " + B['label'] + " " +  B['mc'] + " " + B['tz'] +  "，".join(options) + "。请根据处理要求做出处理，并返回结果,删除选项必须对应到明确的特殊处理要求，不要擅自删除选项。例如，如果处理完后剩余A,B,C三个选项，请返回[A,B,C]"},
        ],
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    completion = sfclient.chat.completions.create(
        model=simplemodel(),
        messages=xuanxiang(json_string),
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    answer=[]
    if 'A' in json_string:
        answer.append(A[0])
    if 'B' in json_string:
        answer.append(A[1])
    if 'C' in json_string:
        answer.append(A[2])
    if 'D' in json_string:
        answer.append(A[3])
    if 'E' in json_string:
        answer.append(A[4])
    if 'F' in json_string:
        answer.append(A[5])
    if 'G' in json_string:
        answer.append(A[6])
    if 'H' in json_string:
        answer.append(A[7])
    if 'I' in json_string:
        answer.append(A[8])
    if 'J' in json_string:
        answer.append(A[9])
    return answer
def aifilter1_1(A, #options
       B, #data
       aiclient,
             qwclient,
             sfclient,
             dw):
    options=[]
    letters = "ABCDEFGHIJKLMN"
    for i in range(len(A)):
        options.append("给定选项" + letters[i]+"，内容为"+A[i] )

    completion = aiclient.chat.completions.create(
        model="glm-4.5-air",
        #model="Qwen/Qwen3-8B",
        #model="ernie-speed-128k",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": " 特殊处理要求一：去掉所有含有“干铺卷材”字样的选项"},
            {"role": "user", "content": " 特殊处理要求二：如果工作内容描述中没有明确提到玻纤网格布，则去掉所有含有“玻纤网格布”字样的选项"},
            {"role": "user", "content": " 特殊处理要求三：如果工作内容描述的是屋面刚性层，则去掉所有精确含有‘卷材’字样的选项"},
            {"role": "user", "content": " 重要提示：选项指的是给定的A、B、C之类的选项，不是指的工作内容中的可能的1、2、3这样罗列的特征"},
            {"role": "user", "content": " 重要提示：除特殊处理要求提及的内容外，不需考虑选项内容与工作内容是否符合，只需要根据特殊处理要求做出处理"},
            {"role": "user", "content": "问题描述： 给定一段工作内容: " + B['label'] + " " +  B['mc'] + " " + B['tz'] +  "，".join(options) + "。请根据处理要求做出处理，并返回结果,删除选项必须对应到明确的特殊处理要求，不要擅自删除选项。例如，如果处理完后剩余A,B,C三个选项，请返回[A,B,C]"},
        ],
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": True},
        #stream=True
    )
    #done_thinking = False
    #json_string=""
    #thinking_json_string=""
    #for chunk in completion:
    #    thinking_chunk = chunk.choices[0].delta.reasoning_content
    #    answer_chunk = chunk.choices[0].delta.content
    #    if thinking_chunk != '':
    #        thinking_json_string = thinking_json_string +  thinking_chunk
    #    elif answer_chunk != '':
    #        if not done_thinking:
    #            done_thinking = True
    #        json_string = json_string + answer_chunk
    json_string = completion.choices[0].message.content
    #print(thinking_json_string)
    print(json_string)
    if len([x for x in json_string if x != ',' and x != '[' and x != ']' and x != ' ' and (x < 'A' or x > 'M')]) < 5:
        answer=[]
        if 'A' in json_string and len(A) > 0:
            answer.append(A[0])
        if 'B' in json_string and len(A) > 1:
            answer.append(A[1])
        if 'C' in json_string and len(A) > 2:
            answer.append(A[2])
        if 'D' in json_string and len(A) > 3:
            answer.append(A[3])
        if 'E' in json_string and len(A) > 4:
            answer.append(A[4])
        if 'F' in json_string and len(A) > 5:
            answer.append(A[5])
        if 'G' in json_string and len(A) > 6:
            answer.append(A[6])
        if 'H' in json_string and len(A) > 7:
            answer.append(A[7])
        if 'I' in json_string and len(A) > 8:
            answer.append(A[8])
        if 'J' in json_string and len(A) > 9:
            answer.append(A[9])
        return answer
    completion = sfclient.chat.completions.create(
        model=simplemodel(),
        messages=xuanxiang(json_string),
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    answer=[]
    if 'A' in json_string:
        answer.append(A[0])
    if 'B' in json_string:
        answer.append(A[1])
    if 'C' in json_string:
        answer.append(A[2])
    if 'D' in json_string:
        answer.append(A[3])
    if 'E' in json_string:
        answer.append(A[4])
    if 'F' in json_string:
        answer.append(A[5])
    if 'G' in json_string:
        answer.append(A[6])
    if 'H' in json_string:
        answer.append(A[7])
    if 'I' in json_string:
        answer.append(A[8])
    if 'J' in json_string:
        answer.append(A[9])
    return answer
def aifilter1_2(A, #options
       B, #data
       aiclient,
             qwclient,
             sfclient,
             dw):
    options=[]
    letters = "ABCDEFGHIJKLMN"
    for i in range(len(A)):
        options.append("给定选项" + letters[i]+"，内容为"+A[i] )

    completion = aiclient.chat.completions.create(
        model="glm-4.5-air",
        #model="Qwen/Qwen3-8B",
        #model="ernie-speed-128k",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": " 特殊处理要求一：如果工作内容描述没有明确的“加浆抹光”字样，则去掉所有含有“加浆抹光”字样的选项"},
            {"role": "user", "content": " 特殊处理要求二：如果工作内容描述没有单独的一道“素水泥浆”工序，则去掉所有含有“素水泥浆”字样的选项"},
            {"role": "user", "content": " 特殊处理要求三：如果选项中同时存在保温砂浆选项跟水泥砂浆选项，则去掉水泥砂浆的选项"},
            {"role": "user", "content": " 重要提示：选项指的是给定的A、B、C之类的选项，不是指的工作内容中的可能的1、2、3这样罗列的特征"},
            {"role": "user", "content": " 重要提示：除特殊处理要求提及的内容外，不需考虑选项内容与工作内容是否符合，只需要根据特殊处理要求做出处理"},
            {"role": "user", "content": "问题描述： 给定一段工作内容: " + B['label'] + " " +  B['mc'] + " " + B['tz'] +  "，".join(options) + "。请根据处理要求做出处理，并返回结果,删除选项必须对应到明确的特殊处理要求，不要擅自删除选项。例如，如果处理完后剩余A,B,C三个选项，请返回[A,B,C]"},
        ],
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": True},
        #stream=True
    )
    #done_thinking = False
    #json_string=""
    #thinking_json_string=""
    #for chunk in completion:
    #    thinking_chunk = chunk.choices[0].delta.reasoning_content
    #    answer_chunk = chunk.choices[0].delta.content
    #    if thinking_chunk != '':
    #        thinking_json_string = thinking_json_string +  thinking_chunk
    #    elif answer_chunk != '':
    #        if not done_thinking:
    #            done_thinking = True
    #        json_string = json_string + answer_chunk
    json_string = completion.choices[0].message.content
    #print(thinking_json_string)
    print(json_string)
    if len([x for x in json_string if x != ',' and x != '[' and x != ']' and x != ' ' and (x < 'A' or x > 'M')]) < 5:
        answer=[]
        if 'A' in json_string and len(A) > 0:
            answer.append(A[0])
        if 'B' in json_string and len(A) > 1:
            answer.append(A[1])
        if 'C' in json_string and len(A) > 2:
            answer.append(A[2])
        if 'D' in json_string and len(A) > 3:
            answer.append(A[3])
        if 'E' in json_string and len(A) > 4:
            answer.append(A[4])
        if 'F' in json_string and len(A) > 5:
            answer.append(A[5])
        if 'G' in json_string and len(A) > 6:
            answer.append(A[6])
        if 'H' in json_string and len(A) > 7:
            answer.append(A[7])
        if 'I' in json_string and len(A) > 8:
            answer.append(A[8])
        if 'J' in json_string and len(A) > 9:
            answer.append(A[9])
        return answer
    completion = sfclient.chat.completions.create(
        model=simplemodel(),
        messages=xuanxiang(json_string),
        extra_body={"thinking": {"type": "disabled"}},
        #extra_body={"enable_thinking": False},
    )
    json_string = completion.choices[0].message.content
    print(json_string)
    answer=[]
    if 'A' in json_string:
        answer.append(A[0])
    if 'B' in json_string:
        answer.append(A[1])
    if 'C' in json_string:
        answer.append(A[2])
    if 'D' in json_string:
        answer.append(A[3])
    if 'E' in json_string:
        answer.append(A[4])
    if 'F' in json_string:
        answer.append(A[5])
    if 'G' in json_string:
        answer.append(A[6])
    if 'H' in json_string:
        answer.append(A[7])
    if 'I' in json_string:
        answer.append(A[8])
    if 'J' in json_string:
        answer.append(A[9])
    return answer
def aifilter2(A, #options
       B, #data
       aiclient,
             qwclient,
             sfclient,
             dw):
    hit_wumian = False
    for entry in A:
        if entry in obj['wumian']:
            hit_wumian=True

    hit_loumian = False
    loumian_entry = ''
    for entry in A:
        if entry in obj['loumian']:
            hit_loumian=True
            loumian_entry = entry
    if hit_wumian and hit_loumian:
        return [x for x in A if x != loumian_entry]
    return A


def postprocess0109(selected, data, aiclient, qwclient, sfclient, label_name, name_dw):
    juancai = [x for x in selected if 'SBS改性沥青防水卷材' in x or 'APP改性沥青防水卷材' in x]
    no_juancai = [x for x in selected if x not in juancai]
    group_juancai = [
       [name_label['10-30'],name_label['10-31']],
       [name_label['10-32'],name_label['10-33']],
       [name_label['10-34'],name_label['10-35']],
       [name_label['10-36'],name_label['10-37']],
       [name_label['10-38'],name_label['10-39']],
       [name_label['10-40'],name_label['10-41']],
       [name_label['10-42'],name_label['10-43']],
       [name_label['10-44'],name_label['10-45']],
    ]
    if len(juancai) > 0:
        hit_group=[]
        for entry in group_juancai:
            if juancai[0] in entry:
                hit_group=entry
        shuang = shuangceng(data,aiclient,sfclient)
        if shuang:
            selected = no_juancai + [hit_group[1]]
        else:
            selected = no_juancai + [hit_group[0]]
            
    if len([x for x in selected if '屋面找平层' in x and '细石混凝土' in x]) > 0:
        zhaoping = zhaopingceng(data,aiclient,sfclient)
        if not zhaoping:
            selected = [x for x in selected if not ('屋面找平层' in x and '细石混凝土' in x)]
    prime = aifilter1_1(selected, data, aiclient, qwclient, sfclient, name_dw)
    prime = aifilter1_2(prime, data, aiclient, qwclient, sfclient, name_dw)
    if data['bianma'].startswith("010902") and '高聚物' in data['tz'] and '改性沥青防水涂料' in data['tz']:##屋面防水
        if '第十章  屋面及防水工程 10.2  平面立面及其它防水 10.2.1  涂刷油类 水泥基渗透结晶 防水材料 二～三遍(厚2mm)' not in prime:
            prime.append('第十章  屋面及防水工程 10.2  平面立面及其它防水 10.2.1  涂刷油类 水泥基渗透结晶 防水材料 二～三遍(厚2mm)') ##需要换
    if data['bianma'].startswith("010902") and '非固化' in data['tz'] and '沥青防水涂料' in data['tz']:##屋面防水
        if '第十章  屋面及防水工程 10.2  平面立面及其它防水 10.2.1  涂刷油类 水泥基渗透结晶 防水材料 二～三遍(厚2mm)' not in prime:
            prime.append('第十章  屋面及防水工程 10.2  平面立面及其它防水 10.2.1  涂刷油类 水泥基渗透结晶 防水材料 二～三遍(厚2mm)') ##需要换
    prime = aifilter2(prime, data, aiclient, qwclient, sfclient, name_dw)##找平层去重
    prime = aifilter4(prime, data, aiclient, qwclient, sfclient, name_dw)##沥青去重
    if data['bianma'].startswith("010902") and '保护层' in data['tz']:##屋面防水保护层
        l = len([x for x in prime if '刚性防水屋面' in x])
        if l==0:
            answer = aifilter3(prime, data, aiclient, qwclient, sfclient, name_dw)
            prime.append(answer[0])
    if '南通补充定额 南通补充定额2016 第十章 屋面及防水工程 干铺法施工水泥彩瓦屋面（砼屋面板上钉钢挂瓦条、顺水条）' in prime:
        prime.append('南通补充定额 南通补充定额2016 第十章 屋面及防水工程 干铺法施工水泥彩瓦屋面（铺瓦）')

    return prime
