import re
import sys

def get_kana_regex(text):
    mapping = {
        'っ': '[つっ]', 'つ': '[つっ]',
        'ゃ': '[やゃ]', 'や': '[やゃ]',
        'ゅ': '[ゆゅ]', 'ゆ': '[ゆゅ]',
        'ょ': '[よょ]', 'よ': '[よょ]',
        'ぁ': '[あぁ]', 'あ': '[あぁ]',
        'ぃ': '[いぃ]', 'い': '[いぃ]',
        'ぅ': '[うぅ]', 'う': '[うぅ]',
        'ぇ': '[えぇ]', 'え': '[えぇ]',
        'ぉ': '[おぉ]', 'お': '[おぉ]',
    }
    pattern = ""
    for char in text:
        pattern += mapping.get(char, re.escape(char))
    return pattern

def clean_for_bolding(text):
    text = re.sub(r'[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩI-V,.]+$', '', text)
    return text.strip()

def merge_lines(lines):
    # Only merge if it's clearly a continuation in the example section
    barrier_re = re.compile(r'^(\*\*|【|⇨|\(\d+\)|[①-⑩]|<\d+>|×|→|‾‾|__)')
    terminators = "。！？」/”" # Sentence/line terminators
    
    merged = []
    in_examples = False
    
    for line in lines:
        stripped = line.strip()
        if not stripped:
            merged.append(line)
            continue
            
        if stripped.startswith('**'):
            in_examples = True
            merged.append(line)
            continue
            
        if stripped.startswith('【') or stripped.startswith('⇨'):
            in_examples = False
            merged.append(line)
            continue
            
        if not in_examples:
            # Preservation mode: never merge in analysis/comparison
            merged.append(line)
            continue
            
        if barrier_re.match(stripped):
            merged.append(line)
            continue
            
        # Continuation candidate in example section
        found = False
        skipped_marker_or_empty = False
        for k in range(len(merged)-1, -1, -1):
            pk = merged[k].strip()
            if not pk: 
                skipped_marker_or_empty = True
                continue # Skip empty lines
            if re.match(r'^<\d+>$', pk):
                skipped_marker_or_empty = True
                continue
            
            # Found the last content line
            last_char = pk[-1] if pk else ""
            if skipped_marker_or_empty or (last_char not in terminators):
                merged[k] = merged[k].rstrip() + stripped + "\n"
                found = True
            break
            
        if not found:
            merged.append(line)
            
    return merged

def bold_headwords(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as f:
        raw_lines = f.readlines()

    lines = merge_lines(raw_lines)

    output = []
    current_var_regexes = []
    is_in_examples = False
    
    hw_regex = re.compile(r'^\s*\*\*([^*\[]+)(?:\[([^*\]]+)\])?\*\*(.*)$')
    
    def get_variations_regex(readings, kanjis):
        base_strings = set()
        for r in readings:
            r_clean = clean_for_bolding(r)
            if not r_clean: continue
            base_strings.add(r_clean)
            base_strings.add(r_clean + "と")
            base_strings.add(r_clean + "に")
            base_strings.add(r_clean + "な")
            base_strings.add(r_clean + "も")
            base_strings.add("お" + r_clean)
            base_strings.add("お" + r_clean + "さま")
            if "かわらず" in r_clean or "変わらず" in r_clean:
                base_strings.add(r_clean.replace("かわらず", "もかわらず").replace("変わらず", "も変わらず"))
                base_strings.add(r_clean.replace("かわらず", "わりませず").replace("変わらず", "わりませず"))
            if r_clean.endswith("て"):
                stem = r_clean[:-1]
                base_strings.add(stem + "いませず")
                base_strings.add(stem + "いまして")
        for k in kanjis:
            k_clean = clean_for_bolding(k)
            if not k_clean: continue
            base_strings.add(k_clean)
            base_strings.add(k_clean + "と")
            base_strings.add(k_clean + "に")
            base_strings.add(k_clean + "な")
        
        sorted_bases = sorted(list(base_strings), key=len, reverse=True)
        return [get_kana_regex(b) for b in sorted_bases]

    def process_sentence(line, var_regexes, line_num, force_warn=False):
        if not var_regexes: return line
        if '/' in line:
            parts = line.split('/')
            ja_part = parts[0]
            cn_part = '/' + '/'.join(parts[1:])
        else:
            ja_part, cn_part = line, ""
        if "**" in ja_part: return line
        
        new_ja_part = ja_part
        matched = False
        for v_reg in var_regexes:
            pattern = re.compile(v_reg)
            if pattern.search(new_ja_part):
                new_ja_part = pattern.sub(lambda m: f"**{m.group(0)}**", new_ja_part)
                matched = True
                break
                
        if not matched and force_warn:
            if re.search(r'([①-⑩]|\(\d+\))', line) and '/' in line:
                text_only = re.sub(r'([①-⑩]|\(\d+\))', '', ja_part).strip()
                if text_only and any('\u3040' <= c <= '\u30FF' or '\u4E00' <= c <= '\u9FFF' for c in text_only):
                    print(f"Warning: No bolding in line {line_num}: {line.strip()}", file=sys.stderr)
        return new_ja_part + cn_part

    for i, line in enumerate(lines):
        line_num = i + 1
        stripped = line.strip()
        if not stripped:
            output.append(line)
            continue
            
        page_match = re.match(r'^<\d+>$', stripped)
        if page_match:
            output.append(line)
            continue
            
        hw_match = hw_regex.match(line)
        if hw_match:
            reading_raw = hw_match.group(1).strip()
            kanji_raw = hw_match.group(2).strip() if hw_match.group(2) else ""
            tail = hw_match.group(3).strip()
            
            readings = [r.strip() for r in reading_raw.split('・')]
            kanjis = [k.strip() for k in kanji_raw.split('・')] if kanji_raw else []
            current_var_regexes = get_variations_regex(readings, kanjis)
            
            if tail:
                processed_tail = process_sentence(tail, current_var_regexes, line_num, True)
                kanji_str = f" [{kanji_raw}]" if kanji_raw else ""
                output.append(f"**{reading_raw}{kanji_str}** {processed_tail}\n")
            else:
                output.append(line)
            is_in_examples = True
            continue
            
        if stripped.startswith('【') or stripped.startswith('⇨'):
            is_in_examples = False
            output.append(line)
            continue
            
        if is_in_examples:
            output.append(process_sentence(line, current_var_regexes, line_num, True))
        else:
            output.append(process_sentence(line, current_var_regexes, line_num, False))

    with open(output_file, 'w', encoding='utf-8') as f:
        f.writelines(output)

if __name__ == "__main__":
    bold_headwords(
        r'现代日本语副词用法辞典_gemini.txt',
        r'现代日本语副词用法辞典_final.txt'
    )
