'''
Author: CloudSir
@Github: https://github.com/CloudSir
Date: 2025-12-20 16:31:13
LastEditTime: 2025-12-20 16:31:14
LastEditors: CloudSir
Description: 
'''
import os
import re
import shutil
import sys
from bs4 import BeautifulSoup
from datetime import datetime

def html_to_markdown(html_content):
    """将HTML内容转换为Markdown格式"""
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 处理无序列表
    for ul in soup.find_all('ul'):
        items = ul.find_all('li')
        markdown_items = []
        for item in items:
            # 递归转换列表项内的内容
            item_content = convert_element_to_markdown(item)
            markdown_items.append(f"- {item_content}")
        ul.replace_with(''.join(markdown_items))
    
    # 处理有序列表
    for ol in soup.find_all('ol'):
        items = ol.find_all('li')
        markdown_items = []
        for i, item in enumerate(items, 1):
            # 递归转换列表项内的内容
            item_content = convert_element_to_markdown(item)
            markdown_items.append(f"{i}. {item_content}")
        ol.replace_with(''.join(markdown_items))
    
    # 最后转换整个内容为文本
    return convert_element_to_markdown(soup)

def convert_element_to_markdown(element):
    """递归转换HTML元素为Markdown格式"""
    if isinstance(element, str):
        return element
    
    # 处理不同类型的HTML标签
    tag = element.name
    contents = []
    
    # 先处理子元素
    for child in element.children:
        if hasattr(child, 'name'):
            contents.append(convert_element_to_markdown(child))
        else:
            contents.append(str(child))
    
    content_str = ''.join(contents)
    
    # 根据标签类型转换为相应的Markdown格式
    if tag in ['strong', 'b']:
        # 将strong、b和mark标签转换为Markdown粗体
        return f"**{content_str.strip()}**"
    elif tag in ['mark']:
        # 将mark标签转换为Markdown标记
        return f"=={content_str.strip()}=="
    elif tag in ['em', 'i']:
        # 将em、i标签转换为Markdown斜体
        return f"*{content_str.strip()}*"
    elif tag == 'u':
        # 将u标签转换为Markdown下划线（通常用HTML标签）
        return f"<u>{content_str.strip()}</u>"
    elif tag == 's' or tag == 'del':
        # 将s、del标签转换为Markdown删除线
        return f"~~{content_str.strip()}~~"
    elif tag in ['p', 'div']:
        # 段落和div添加换行
        return content_str.strip() + '\n'
    elif tag == 'br':
        # 换行标签
        return '\n'
    elif tag == 'a':
        # 链接
        href = element.get('href', '')
        return f"[{content_str.strip()}]({href})"
    else:
        # 其他标签，直接返回内容
        return content_str

def extract_memos_to_markdown(tags=None):
    # 读取HTML文件
    html_file = ""
    for filename in os.listdir('.'):  # 遍历当前目录下的所有文件和文件夹
        if filename.endswith('.html'):  # 检查文件是否以.html结尾
            html_file = filename 
            break   # 如果找到，直接返回文件名
    else:
        print("未找到HTML文件")
        return
    print(f"正在处理文件: {html_file}")
    with open(html_file, 'r', encoding='utf-8') as f:
        html_content = f.read()
    
    # 解析HTML
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 如果没有传入标签，则提示用户输入（如果标准输入可用）
    if tags is None:
        if not sys.stdin.isatty():
            # 在非交互式环境中，使用默认标签或空字符串
            tags = ""  # 可以设置为默认标签，如 "#flomo"
            print("在非交互式环境中运行，使用空标签")
        else:
            tags = input("请输入要添加的标签（多个标签用空格分隔，需要加 #）: ").strip()
    
    # 创建flomos文件夹
    if not os.path.exists("flomos"):
        os.makedirs("flomos")
    
    # 查找所有memo div
    memo_divs = soup.find_all('div', class_='memo')
    
    if not memo_divs:
        print("未找到任何memo项")
        return
    
    processed_count = 0
    for memo_div in memo_divs:
        # 提取时间
        time_div = memo_div.find('div', class_='time')
        if time_div:
            time_str = time_div.get_text().strip()
            # 将时间转换为YYYYMMDDHHMMSS格式
            dt = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
            filename = dt.strftime('%Y%m%d%H%M%S') + '.md'
        else:
            # 如果没有时间，默认使用当前时间
            dt = datetime.now()
            filename = dt.strftime('%Y%m%d%H%M%S') + '.md'
        
        # 提取内容并转换为Markdown格式
        content_div = memo_div.find('div', class_='content')
        content = ""
        if content_div:
            # 将HTML内容转换为Markdown格式
            content = html_to_markdown(str(content_div))
        
        # 处理附件
        files_div = memo_div.find('div', class_='files')
        if files_div:
            img_tags = files_div.find_all('img')
            for img_tag in img_tags:
                img_src = img_tag.get('src')
                if img_src:
                    # 提取文件名
                    img_filename = os.path.basename(img_src)
                    # 复制附件到flomos文件夹
                    if os.path.exists(img_src):
                        shutil.copy(img_src, os.path.join("flomos", img_filename))
                        print(f"已复制附件: {img_filename}")
                    else:
                        print(f"警告: 附件文件不存在 {img_src}")
                    
                    # 在内容后添加附件引用
                    content += f"\n![[{img_filename}]]"
        
        # 添加标签到内容
        if tags:
            content += f"\n\n{tags}"
        
        # 保存为Markdown文件
        md_file_path = os.path.join("flomos", filename)
        with open(md_file_path, 'w', encoding='utf-8') as md_file:
            md_file.write(content)
        
        print(f"已保存: {filename}")
        processed_count += 1
    
    print(f"处理完成，共处理了 {processed_count} 个memo项")

if __name__ == "__main__":
    # 可以通过命令行参数传递标签
    if len(sys.argv) > 1:
        tags = sys.argv[1]
    else:
        tags = None
    
    extract_memos_to_markdown(tags)