import pandas as pd
import numpy as np
import re

def parse_and_execute_commands(processed, user_input, fix, after, popped_row):
    commands = [cmd.strip() for cmd in user_input.split(',') if not cmd.strip().startswith('#')]
    for command in commands:
        condition, cmd = parse_conditional_command(command)
        nfix = [item.translate(str.maketrans('', '', '{}[]')) for item in fix if not item.startswith('#')]
        if check_condition(processed+nfix, condition, popped_row):
            processed = execute_command(processed, cmd, fix, after)
    return processed

def parse_conditional_command(command):
    match = re.match(r"\((.*?)\)\:(.*)", command)
    if match:
        return match.groups()
    return '', command

def check_condition(processed, condition, popped_row):
    if not condition:
        return True
    sub_conditions = re.split(r'\)\s*&\s*\(', condition)
    sub_conditions = [re.sub(r'^\(|\)$', '', cond) for cond in sub_conditions]

    results = []
    for sub_cond in sub_conditions:
        if '&' in sub_cond:
            results.append(all(check_condition(processed, cond, popped_row) for cond in sub_cond.split('&')))
        elif '|' in sub_cond:
            results.append(any(check_condition(processed, cond, popped_row) for cond in sub_cond.split('|')))
        else:
            if sub_cond in ['e', 'q', 's', 'g']:
                results.append(sub_cond == popped_row['rating'])
            elif sub_cond in ['~e', '~q', '~s', '~g']:
                results.append(sub_cond != popped_row['rating'])
            # PM
            elif sub_cond.startswith('*'):
                results.append(sub_cond[1:] in processed)
            # NOT IN
            elif sub_cond.startswith('~!'):
                results.append(sub_cond[2:] not in processed)
            elif sub_cond.startswith('~'):
                results.append(any(sub_cond[1:] not in element for element in processed))
            # CONTAIN
            else:
                results.append(any(sub_cond in element for element in processed))
    return all(results)

def execute_command(processed, command, fix, after):
    if '+=' in command:
        keyword, addition = command.split('+=', 1)
        addition = addition.replace('^', ', ')
        #addiction split 해서 프롬프트 존재하는지 체크 필요
        return insert_text_after_keyword(processed, keyword, addition, fix, after)
    elif '=' in command:
        keyword, replacement = command.split('=', 1)
        if keyword in processed:
            replacement = replacement.replace('^', ', ')
            #replacement split 해서 프롬프트 존재하는지 체크 필요
            index = processed.index(keyword)
            processed[index] = replacement
    return processed

def insert_text_after_keyword(processed, user_keyword, user_additional_keyword, fix, after):
    if user_keyword == "prompt":
        processed.append(user_additional_keyword)
    elif user_keyword == "prefix":
        fix.append(user_additional_keyword)
    elif user_keyword == "postfix":
        after.append(user_additional_keyword)
    elif user_keyword in processed:
        index = processed.index(user_keyword) + 1
        processed.insert(index, user_additional_keyword)
    return processed

def find_keyword_index(general):
    # boys와 girls 리스트의 원소가 있는지 확인 및 인덱스 저장
    boys = ["1boy", "2boys", "3boys", "4boys", "5boys", "6+boys"]
    girls = ["1girl", "2girls", "3girls", "4girls", "5girls", "6+girls"]
    #others = ["1other", "2others", "3others", "4others", "5others", "6+others"]
    boys_indices = [i for i, item in enumerate(general[:6]) if item in boys]
    girls_indices = [i for i, item in enumerate(general[:6]) if item in girls]

    # case 1과 case 2: girls 리스트의 원소 찾기
    if girls_indices:
        return girls_indices[0]+1
    
    # case 3: boys 리스트의 원소 찾기
    if boys_indices:
        return boys_indices[0]+1

    # case 4: 해당 사항 없음
    # 2월 12일에 해당 부분 return 2 -> return 0 으로 수정하였으며 이 부분 트래킹 필요
    return 0

def process_list(temp_fixed):
    i = 0
    while i < len(temp_fixed):
        if ', ' in temp_fixed[i]:
            # 해당 원소를 처리하는 함수에 전달하고 결과를 받음
            processed_items = process_fix_prompt(temp_fixed[i])
            # 원래 원소를 제거
            temp_fixed.pop(i)
            # 처리된 원소들을 현재 인덱스에 삽입
            for item in reversed(processed_items):
                temp_fixed.insert(i, item)
            # 삽입된 원소들을 건너뛰기 위해 인덱스 조정
            i += len(processed_items)
        else:
            i += 1
    return temp_fixed

def process_fix_prompt(fix_prompt):
    fix = []
    lt_count = 0  # '<' 문자 개수 추적
    current_item = ""  # 현재 항목을 결합하기 위한 변수

    # fix_prompt를 쉼표로 분리하고 각 항목을 순회
    for item in fix_prompt.split(','):
        item = item.strip()  # 공백 제거

        if '<' in item:
            lt_count += item.count('<')  # '<' 발견 시 카운트 증가
            lt_count -=  item.count('>')
            if current_item:  # 이미 current_item에 값이 있는 경우 쉼표와 공백 추가
                current_item += ", "
            if lt_count <= 0:  # lt_count가 0이면 일반 항목으로 처리
                fix.append(item)
            else:
                current_item += item  # 현재 항목에 추가
        elif '>' in item:
            lt_count -= item.count('>')  # '>' 발견 시 카운트 감소
            current_item += ", " + item  # '>'가 있는 항목도 현재 항목에 추가
            if lt_count == 0:  # '<'와 '>'의 개수가 매칭되면 fix에 추가하고 current_item 초기화
                fix.append(current_item)
                current_item = ""
        else:
            if lt_count <= 0:  # lt_count가 0이면 일반 항목으로 처리
                fix.append(item)
            else:  # lt_count가 0이 아니면 현재 항목에 계속해서 추가
                current_item += ", " + item

    # 마지막에 남은 current_item 처리
    if current_item:
        fix.append(current_item)

    return fix

def RFP(popped_row, fix_prompt, after_prompt, auto_hide_prompt, rm_a, rm_s, rm_c, rm_loc, rm_color, nsfw, data, magic_word):
    boys = ["1boy", "2boys", "3boys", "4boys", "5boys", "6+boys"]
    girls = ["1girl", "2girls", "3girls", "4girls", "5girls", "6+girls"]
    general = [item.strip() for item in popped_row['general'].split(',')]
    special_word_check = fix_prompt+', '+after_prompt
    special_word_check = [item.strip() for item in special_word_check.split(',')]
    special_word_check = [item for item in special_word_check if item.startswith('*')]
    colors = ['black','white','blond','silver','gray','yellow','blue','purple','red','pink','brown','orange','green','aqua','gradient']
    exc = []
    for keyword in general:
        if keyword == '!' or keyword == '!?' or keyword == '!!':
            exc.append(keyword)
    if exc:
        for keyword in exc:
            general.remove(keyword)
        general[3:3] = exc

    if nsfw == 1:
        nsfw_word = []
        for keyword in general:
            if keyword in data.qe_word or keyword in data.bag_of_tags or "horns" in keyword or "(" in keyword or keyword in boys or keyword in girls:
                nsfw_word.append(keyword)
        nsfw_word = list(set(nsfw_word))
        nsfw_word.sort()
        general = nsfw_word
    if rm_loc == 1:
        temp_general = []
        locations = ['airplane interior', 'airport', 'apartment', 'arena', 'armory', 'bar', 'barn', 'bathroom', 'bathtub', 'bedroom', 'bell tower', 'billiard room', 'book store', 'bowling alley', 'bunker', 'bus interior', 'butcher shop', 'cafe', 'cafeteria', 'car interior', 'casino', 'castle', 'catacomb', 'changing room', 'church', 'classroom', 'closet', 'construction site', 'convenience store', 'convention hall', 'court', 'dining room', 'drugstore', 'ferris wheel', 'flower shop', 'gym', 'hangar', 'hospital', 'hotel room', 'hotel', 'infirmary', 'izakaya', 'kitchen', 'laboratory', 'library', 'living room', 'locker room', 'mall', 'messy room', 'mosque', 'movie theater', 'museum', 'nightclub', 'office', 'onsen', 'ovservatory', 'phone booth', 'planetarium', 'pool', 'prison', 'refinery', 'restaurant', 'restroom', 'rural', 'salon', 'school', 'sex shop', 'shop', 'shower room', 'skating rink', 'snowboard shop', 'spacecraft interior', 'staff room', 'stage', 'supermarket', 'throne', 'train station', 'tunnel', 'airfield', 'alley', 'amphitheater', 'aqueduct', 'bamboo forest', 'beach', 'blizzard', 'bridge', 'bus stop', 'canal', 'canyon', 'carousel', 'cave', 'cliff', 'cockpit', 'conservatory', 'cross walk', 'desert', 'dust storm', 'flower field', 'forest', 'garden', 'gas staion', 'gazebo', 'geyser', 'glacier', 'graveyard', 'harbor', 'highway', 'hill', 'island', 'jungle', 'lake', 'market', 'meadow', 'nuclear powerplant', 'oasis', 'ocean bottom', 'ocean', 'pagoda', 'parking lot', 'playground', 'pond', 'poolside', 'railroad', 'rainforest', 'rice paddy', 'roller coster', 'rooftop', 'rope bridge', 'running track', 'savannah', 'shipyard', 'shirine', 'skyscraper', 'soccor field', 'space elevator', 'stair', 'starry sky', 'swamp', 'tidal flat', 'volcano', 'waterfall', 'waterpark', 'wheat field', 'zoo', 'white background', 'simple background', 'grey background', 'gradient background', 'blue background', 'black background', 'yellow background', 'pink background', 'red background', 'brown background', 'green background', 'purple background', 'orange background']
        for keyword in general:
            if keyword in locations:
                temp_general.append(keyword)
        for keyword in temp_general:
            general.remove(keyword)
    if rm_color == 1:
        temp_general = []
        for keyword in general:
            if any(color in keyword for color in colors):
                temp_general.append(keyword)
        for keyword in temp_general:
            general.remove(keyword)
    if rm_c == 1:
        temp_general = []
        for keyword in general:
            if keyword in data.bag_of_tags:
                temp_general.append(keyword)
        for keyword in temp_general:
            general.remove(keyword)
    
    #NAIA_random_function_core.process_fix_prompt()
    fix = process_fix_prompt(fix_prompt)

    at_first = []
    for fp in fix:
        if fp.startswith('*'):
            at_first.append(fp[1:])
    if at_first:
        for af in at_first:
            if '*'+af in fix:
                fix.remove('*'+af)
    if rm_a == 0:
        if popped_row['artist']:
            artists = [item.strip() for item in popped_row['artist'].split(',')]
            artist = ["artist:" + _artist for _artist in artists]
            fix = fix + artist
    if rm_s == 0:
        if popped_row['copyright']:
            series = [item.strip() for item in popped_row['copyright'].split(',')]
        else:
            series = []
        fix = fix + series
    after = [item.strip() for item in after_prompt.split(',')]
    auto_hide = [item.strip() for item in auto_hide_prompt.split(',') if not item.strip().startswith('#')] + ["| |", ":|", "\||/", "<|> <|>", "|| ||", ";|"]
    fix_index = find_keyword_index(general)
    processed = general.copy()
    temp_hide_prompt = []
    for keyword in processed:
        if keyword in auto_hide:
            temp_hide_prompt.append(keyword)
    for keyword in temp_hide_prompt:
        processed.remove(keyword)
    #여기에서 문제의 magic word 처리
    if "cond" in magic_word and magic_word["cond"]:
        user_input = magic_word["cond"]
        processed = parse_and_execute_commands(processed, user_input, fix, after, popped_row)
    
    processed[fix_index:fix_index] = fix
    processed += after

    if rm_c == 0 and '*(remove character name)' not in special_word_check and '*(set character name after prefix)' not in special_word_check and '*(set character name before prefix)' not in special_word_check:
        if popped_row['character']:
            character = [item.strip() for item in popped_row['character'].split(',')]
            processed[fix_index:fix_index] = character
            fix_index+=len(character)
    elif rm_c == 0 and '*(set character name after prefix)' in special_word_check:
        if popped_row['character']:
            character = [item.strip() for item in popped_row['character'].split(',')]
            processed[fix_index+len(fix):fix_index+len(fix)] = character
            #fix_index+=len(character)
    elif rm_c == 0 and '*(set character name before prefix)' in special_word_check:
        if popped_row['character']:
            character = [item.strip() for item in popped_row['character'].split(',')]
            processed[fix_index+1:fix_index+1] = character
            fix_index+=len(character)
    if magic_word["random_artist"] == True:
        processed.insert(fix_index, magic_word["random_artist_name"])
        
    boy_in_processed = girl_in_processed = None
    for boy in boys:
        if boy in processed:
            boy_in_processed = boy
            break

    for girl in girls:
        if girl in processed:
            girl_in_processed = girl
            break
        
    if boy_in_processed and girl_in_processed:
        boy_index = processed.index(boy_in_processed)
        girl_index = processed.index(girl_in_processed)
        if boy_index > girl_index:
            processed.pop(boy_index)
            processed.insert(girl_index, boy_in_processed)

    s_word = ['*(remove character name)', '*(set character name after prefix)', '*(set character name before prefix)']
    for keyword in s_word:
        if keyword in processed:
            processed.remove(keyword)
            
    if at_first:
        processed = at_first + processed
    for i, key in enumerate(processed):
        if key.startswith('#'): processed[i] = '\n\n'+key+'\n'
    return ', '.join(processed), popped_row['rating']