import os
import re

server_path = r'e:\Git\antigravity-expleration\outlook-desktop-mcp\src\outlook_desktop_mcp\server.py'
formatting_path = r'e:\Git\antigravity-expleration\outlook-desktop-mcp\src\outlook_desktop_mcp\utils\formatting.py'

# 1. Update formatting.py
with open(formatting_path, 'r', encoding='utf-8') as f:
    text = f.read()

if 'import urllib.parse' not in text:
    text = text.replace('import re\n', 'import re\nimport urllib.parse\n')

# Convert item.Subject or "(no subject)" -> urllib.parse.unquote(item.Subject) if item.Subject else "(no subject)"
text = re.sub(
    r'item\.Subject or "\([^)]+\)"',
    r'urllib.parse.unquote(item.Subject) if item.Subject else "(no subject)"',
    text
)

with open(formatting_path, 'w', encoding='utf-8') as f:
    f.write(text)

# 2. Update server.py
with open(server_path, 'r', encoding='utf-8') as f:
    text = f.read()

if 'import urllib.parse' not in text:
    text = text.replace('import os\n', 'import os\nimport urllib.parse\n')

# Add ensure_ascii=False to json.dumps wherever it exists
text = text.replace('json.dumps(results, indent=2, default=str)', 'json.dumps(results, indent=2, ensure_ascii=False, default=str)')
text = text.replace('json.dumps(format_email_full(item), indent=2, default=str)', 'json.dumps(format_email_full(item), indent=2, ensure_ascii=False, default=str)')
text = text.replace('json.dumps(format_email_full(items.Item(1)), indent=2, default=str)', 'json.dumps(format_email_full(items.Item(1)), indent=2, ensure_ascii=False, default=str)')
text = text.replace('json.dumps(format_event_full(item), indent=2, default=str)', 'json.dumps(format_event_full(item), indent=2, ensure_ascii=False, default=str)')
text = text.replace('json.dumps(format_task_full(item), indent=2, default=str)', 'json.dumps(format_task_full(item), indent=2, ensure_ascii=False, default=str)')
text = text.replace('json.dumps(folders, indent=2, default=str)', 'json.dumps(folders, indent=2, ensure_ascii=False, default=str)')

# Replace single-line or multi-line dictionary json.dumps
text = re.sub(r'json\.dumps\(\{(.*?)\},\s*indent=2,\s*default=str\)', r'json.dumps({\1}, indent=2, ensure_ascii=False, default=str)', text, flags=re.DOTALL)
text = re.sub(r'json\.dumps\(\{(.*?)\},\s*indent=2\)', r'json.dumps({\1}, indent=2, ensure_ascii=False)', text, flags=re.DOTALL)

# Decode attachment Filename when listing
text = text.replace('"filename": att.FileName,', '"filename": urllib.parse.unquote(att.FileName),')

# Decode and handle path separators gracefully when saving attachments
old_save_att = """        att = item.Attachments.Item(attachment_index)
        if not save_directory:
            save_directory = os.path.join(os.path.expanduser("~"), "Downloads")
        os.makedirs(save_directory, exist_ok=True)
        save_path = os.path.join(save_directory, att.FileName)
        att.SaveAsFile(save_path)
        return json.dumps({
            "status": "saved",
            "filename": att.FileName,"""

new_save_att = """        att = item.Attachments.Item(attachment_index)
        if not save_directory:
            save_directory = os.path.join(os.path.expanduser("~"), "Downloads")
        
        # URL 디코딩 및 OS에 맞는 경로 통합 적용
        clean_filename = urllib.parse.unquote(att.FileName)
        
        # 윈도우(\\), 유닉스(/) 슬래시 혼용 방지를 위한 기준 정규화
        normalized_filename = clean_filename.replace("/", os.sep).replace("\\\\", os.sep)
        save_path = os.path.normpath(os.path.join(save_directory, os.path.basename(normalized_filename)))
        
        # 상위 디렉터리 보장
        os.makedirs(os.path.dirname(save_path) or save_directory, exist_ok=True)
        
        att.SaveAsFile(save_path)
        return json.dumps({
            "status": "saved",
            "filename": clean_filename,"""

text = text.replace(old_save_att, new_save_att)

with open(server_path, 'w', encoding='utf-8') as f:
    f.write(text)

print("Refactor complete")
