import sys, os, time, re

list_dir = "./"
brand_dir = "brands/"
def findBrand(argv):
    listf = open(list_dir + "products.csv", "r")
    brandf = open(brand_dir + "brands.csv", "r")

    outputbrand = "related_brands.csv"
    outputproduct = "new_product.csv"
    obf = open(outputbrand, "w")
    opf = open(outputproduct, "w")

    brands = []
    brandlines = {}
    for line in brandf:
        brand = line.split("; ")[0]
        brandlines[brand] = line

        # print(brand)
        brands.append(brand)

    not_found = []
    for line in listf:
        fields = line.split("; ")
        key = None
        if fields[0] != "":
            key = fields[0]
        elif fields[1] != "":
            key = fields[1]
        else:
            print("No product key !!!!!!!!")
            return
        found_flag = False
        for brand in brands:
            if key.startswith(brand):
                found_flag = True
                # print("%s-------->%s" % (key, brand))
                newbls = brandlines[brand].split("; ")
                newbls = newbls[:2] + [newbls[2].split(" ")[0]] + newbls[3:]
                if len(newbls) != 4:
                    print(newbls)
                    return
                obf.write("; ".join(newbls))

                newline = fields[:2]

                score = float(fields[2]) / 2
                newline.append(str(score))

                comment_num = ''
                for ch in fields[3]:
                    if ch == "人":
                        break
                    try:
                        temp = int(ch)
                        comment_num += ch
                    except:
                        continue
                newline.append(str(comment_num))

                if fields[4] != "":
                    temp = fields[4].split("·")
                    if len(temp) == 2:
                        newline.append(re.sub(r'\s+','', temp[0]))
                        price = re.sub(r'\s+','', temp[1])
                        price = price.split('/')[0]
                        if price[0] != "¥":
                            print(price)
                            return
                        newline.append(price[1:])
                    else:
                        newline.append(re.sub(r'\s+','', temp[0]))
                        newline.append("")
                else:
                    newline += ["", ""]

                newline += fields[5:]
                if len(newline) != 8:
                    print(newline)
                    return

                opf.write("; ".join(newline))
                break
        if not found_flag:
            not_found.append(key)


    # print("===================totally %s product not found=========================" % len(not_found))
    # for nf in not_found:
    #     print(nf)


if __name__=='__main__':
    findBrand(sys.argv)