import json
import re

def to_html(text):
    if not text:
        return ""
    
    # Ruby Tags: 字[假名] -> <ruby>字<rt>假名</rt></ruby>
    # We restrict the bracket content to be Hiragana/Katakana to avoid matching kanji-in-brackets (headwords)
    # Hiragana: \u3040-\u309F, Katakana: \u30A0-\u30FF, Half-width: \uFF66-\uFF9F
    text = re.sub(r'([^\s\[\]])\[([\u3040-\u309F\u30A0-\u30FF\uFF66-\uFF9F]+)\]', r'<ruby>\1<rt>\2</rt></ruby>', text)
    
    # Bold: **text** -> <b>text</b>
    text = re.sub(r'\*\*([^*]+)\*\*', r'<b>\1</b>', text)
    
    # Underline: __text__ -> <u>text</u>
    text = re.sub(r'__([^_]+)__', r'<u>\1</u>', text)
    
    # Overline: ‾‾text‾‾ -> <span class="overline">text</span>
    text = re.sub(r'‾‾([^‾]+)‾‾', r'<span class="overline">\1</span>', text)
    
    # Newlines: \n -> <br/>
    text = text.replace('\n', '<br/>')
    
    return text

def format_hw_header(hw):
    # Specialized formatting for the main headword in the header
    # Format: Reading [Kanji] or just Reading
    match = re.match(r'^([^\[\]]+)(?:\[([^\[\]]+)\])?$', hw)
    if match:
        reading = match.group(1)
        kanji = match.group(2)
        if kanji:
            return f'<span class="hw_reading">{reading}</span> <span class="hw_kanji">【{kanji}】</span>'
        return f'<span class="hw_reading">{reading}</span>'
    return to_html(hw)

def generate_mdx(json_file, mdx_file, css_file):
    with open(json_file, 'r', encoding='utf-8') as f:
        entries = json.load(f)

    mdx_output = []
    
    for entry in entries:
        main_hw = entry["main_headword"]
        
        # HTML Content
        html = [
            f'<link rel="stylesheet" type="text/css" href="XDRYYFCD.css">',
            f'<div class="entry">',
            f'  <div class="hw_header">{format_hw_header(main_hw)}</div>',
            f'  <div class="definition">{to_html(entry["definition"])}</div>',
        ]
        
        # Examples
        if entry["examples"]:
            html.append('  <div class="examples_section">')
            for eg in entry["examples"]:
                if "group" in eg:
                    html.append(f'    <div class="example_group">')
                    html.append(f'      <span class="group_id">{eg["group"]}</span>')
                    if "header" in eg:
                        html.append(f'      <span class="group_header">{to_html(eg["header"])}</span>')
                    for item in eg["items"]:
                        html.append(f'      <div class="example_item">')
                        html.append(f'        <span class="item_id">{item["id"]}</span>')
                        html.append(f'        <span class="ja">{to_html(item["ja"])}</span>')
                        if item["cn"]:
                            html.append(f'        <span class="cn">{to_html(item["cn"])}</span>')
                        html.append(f'      </div>')
                    html.append(f'    </div>')
                else:
                    # Top-level item
                    html.append(f'    <div class="example_item">')
                    html.append(f'      <span class="item_id">{eg["id"]}</span>')
                    html.append(f'      <span class="ja">{to_html(eg["ja"])}</span>')
                    if eg.get("cn"):
                        html.append(f'      <span class="cn">{to_html(eg["cn"])}</span>')
                    html.append(f'    </div>')
            html.append('  </div>')
            
        # Sections
        for sec_name, sec_text in entry["sections"].items():
            html.append(f'  <div class="section {sec_name}">')
            html.append(f'    <span class="section_title">【{sec_name}】</span>')
            html.append(f'    <div class="section_content">{to_html(sec_text)}</div>')
            html.append(f'  </div>')
            
        # References
        if "references" in entry:
            html.append(f'  <div class="references">')
            html.append(f'    <span class="ref_marker">⇨</span>')
            ref_links = [f'<a href="entry://{r}">{r}</a>' for r in entry["references"]]
            html.append(f'    <span class="ref_list">{", ".join(ref_links)}</span>')
            html.append(f'  </div>')
            
        # Page Number
        if entry["page"]:
            html.append(f'  <div class="page_num">P.{entry["page"]}</div>')
            
        html.append('</div>')
        
        # Append main entry
        mdx_output.append(main_hw)
        mdx_output.append("".join(html))
        mdx_output.append("</>")
        
        # Link Entries
        links = set()
        for r in entry["readings"]:
            if r != main_hw: links.add(r)
        for k in entry.get("kanjis", []):
            if k != main_hw: links.add(k)
            
        for link in sorted(list(links)):
            if link:
                mdx_output.append(link)
                mdx_output.append(f"@@@LINK={main_hw}")
                mdx_output.append("</>")

    with open(mdx_file, 'w', encoding='utf-8') as f:
        f.write("\n".join(mdx_output))

    # Updated CSS
    css_content = """
.entry { font-family: 'Inter', 'Noto Sans JP', sans-serif; line-height: 1.6; color: #333; background: white; border-radius: 12px; padding: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); border: 1px solid #eee; margin-bottom: 20px; position: relative; }
.hw_header { font-size: 1.5em; font-weight: bold; color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 5px; margin-bottom: 15px; }
.hw_reading { color: #2980b9; }
.hw_kanji { color: #7f8c8d; font-size: 0.8em; margin-left: 10px; }
.definition { font-size: 1.1em; margin-bottom: 20px; color: #444; }
.examples_section { margin-left: 10px; border-left: 3px solid #e0e0e0; padding-left: 15px; margin-bottom: 20px; }
.example_group { margin-bottom: 15px; }
.group_id { font-weight: bold; color: #e67e22; margin-right: 5px; }
.group_header { font-weight: bold; color: #7f8c8d; }
.example_item { margin-bottom: 10px; display: block; }
.item_id { font-weight: bold; color: #3498db; margin-right: 8px; font-size: 0.9em; }
.ja { display: inline; font-size: 1.05em; }
.cn { display: block; color: #666; font-size: 0.95em; margin-left: 1.5em; border-left: 2px solid #f0f0f0; padding-left: 8px; }
.section { margin-top: 15px; padding: 10px; border-radius: 8px; }
.section.解析 { background-color: #e8f4fd; border: 1px solid #d1e9f9; }
.section.比较 { background-color: #fef9e7; border: 1px solid #f9e79f; }
.section_title { font-weight: bold; color: #2980b9; margin-bottom: 5px; display: block; }
.section_content { font-size: 0.95em; color: #555; }
.references { margin-top: 20px; border-top: 1px dashed #ccc; padding-top: 10px; font-size: 0.9em; }
.ref_marker { color: #e74c3c; font-weight: bold; margin-right: 5px; }
.ref_list a { color: #3498db; text-decoration: none; margin-right: 10px; }
.ref_list a:hover { text-decoration: underline; }
.page_num { position: absolute; bottom: 10px; right: 15px; font-size: 0.8em; color: #bbb; font-style: italic; }
.overline { text-decoration: overline; }
b { color: #e74c3c; }
ruby rt { font-size: 0.5em; color: #888; }
"""
    with open(css_file, 'w', encoding='utf-8') as f:
        f.write(css_content)

if __name__ == "__main__":
    generate_mdx(
        r'e:\github\japanese10\现代日本语副词用法辞典.json',
        r'e:\github\japanese10\mdx.txt',
        r'e:\github\japanese10\XDRYYFCD.css'
    )
