#!/usr/bin/env python3
"""把HTML报告中file-cell里的纯文本文件名转换为可点击链接"""
import re
import os
import urllib.parse

HTML_PATH = '/data/www/files/yjs-cyl-2026-report.html'
BASE_DIR = '/data/www/files/2026-yjs-cyl'

# 收集所有实际存在的文件路径（递归扫描）
file_map = {}  # 文件名 -> 相对路径（相对于HTML所在目录）
for root, dirs, files in os.walk(BASE_DIR):
    for f in files:
        full = os.path.join(root, f)
        rel = os.path.relpath(full, '/data/www/files/')
        # URL编码
        encoded = urllib.parse.quote(rel)
        file_map[f] = encoded

# 也处理目录下的直接文件
for f in os.listdir(BASE_DIR):
    full = os.path.join(BASE_DIR, f)
    if os.path.isfile(full):
        encoded = urllib.parse.quote(os.path.relpath(full, '/data/www/files/'))
        file_map[f] = encoded

print(f"找到 {len(file_map)} 个文件")

# 读取HTML
with open(HTML_PATH, 'r', encoding='utf-8') as f:
    html = f.read()

# 匹配所有 file-cell 的td内容
# 模式: <td class="file-cell">文件名1, 文件名2, ...</td>
pattern = r'<td class="file-cell">(.*?)</td>'

def replace_file_cell(match):
    content = match.group(1)
    # 按逗号分割文件名（注意可能有中文逗号）
    # 先统一处理：用逗号分割
    parts = re.split(r',\s*', content.strip())
    links = []
    for part in parts:
        part = part.strip()
        if not part:
            continue
        # 查找对应的文件路径
        if part in file_map:
            href = file_map[part]
            links.append(f'<a href="{href}" target="_blank" class="file-link" style="display:inline-block;margin:2px 4px;padding:2px 8px;background:rgba(78,205,196,0.15);border:1px solid rgba(78,205,196,0.3);border-radius:4px;color:#4ECDC4;text-decoration:none;font-size:12px;">📂{part}</a>')
        else:
            # 模糊匹配
            found = False
            for real_name in file_map:
                if part in real_name or real_name in part:
                    href = file_map[real_name]
                    links.append(f'<a href="{href}" target="_blank" class="file-link" style="display:inline-block;margin:2px 4px;padding:2px 8px;background:rgba(78,205,196,0.15);border:1px solid rgba(78,205,196,0.3);border-radius:4px;color:#4ECDC4;text-decoration:none;font-size:12px;">📂{part}</a>')
                    found = True
                    break
            if not found:
                # 最后尝试直接用文件名作为路径
                encoded = urllib.parse.quote(f'2026-yjs-cyl/{part}')
                links.append(f'<a href="{encoded}" target="_blank" class="file-link" style="display:inline-block;margin:2px 4px;padding:2px 8px;background:rgba(78,205,196,0.15);border:1px solid rgba(78,205,196,0.3);border-radius:4px;color:#4ECDC4;text-decoration:none;font-size:12px;">📂{part}</a>')
    
    return f'<td class="file-cell">{"".join(links)}</td>'

new_html = re.sub(pattern, replace_file_cell, html, flags=re.DOTALL)

# 写回
with open(HTML_PATH, 'w', encoding='utf-8') as f:
    f.write(new_html)

# 统计替换了多少
count = len(re.findall(pattern, html, flags=re.DOTALL))
print(f"替换了 {count} 个 file-cell")

# 验证
with open(HTML_PATH, 'r', encoding='utf-8') as f:
    verify = f.read()
verify_count = verify.count('file-link')
print(f"HTML中现在有 {verify_count} 个 file-link 链接")
