#!/usr/bin/env python3
"""Fix broken file links - URL encode spaces."""
import re
import urllib.parse

HTML_FILE = "/data/www/files/2026-yjs-lzy-2026-report.html"

with open(HTML_FILE, 'r', encoding='utf-8') as f:
    content = f.read()

# Fix: URL-encode spaces in href links
# Pattern: href="2026-yjs-lzy/...spaces..."
def fix_href(match):
    full = match.group(0)
    path = match.group(1)
    # URL-encode the path (encode spaces as %20, keep Chinese chars)
    encoded = urllib.parse.quote(path, safe='/')
    return f'href="{encoded}"'

fixed_content = re.sub(r'href="(2026-yjs-lzy/[^"]+)"', fix_href, content)

if fixed_content != content:
    with open(HTML_FILE, 'w', encoding='utf-8') as f:
        f.write(fixed_content)
    print("链接已修复（URL编码空格）")
    
    # Count changes
    import difflib
    old_links = set(re.findall(r'href="(2026-yjs-lzy/[^"]+)"', content))
    new_links = set(re.findall(r'href="(2026-yjs-lzy/[^"]+)"', fixed_content))
    changed = old_links - new_links
    print(f"修改了 {len(changed)} 个链接")
    for l in sorted(changed):
        print(f"  {l}")
else:
    print("无需修复")

# Now verify the 4 previously broken links
import subprocess
broken = [
    "2026-yjs-lzy/%E4%B9%90%E5%B1%B1/%E5%B3%A8%E8%BE%B9%E5%BD%9D%E6%97%8F%E8%87%AA%E6%B2%BB%E5%8E%BF%E5%8E%BF%E5%A7%94%E7%BB%84%E7%BB%87%E9%83%A82026%20%E5%B9%B4%E9%83%A8%E9%97%A8%E9%A2%84%E7%AE%97.pdf",
]

print("\n验证修复后的链接:")
for link in broken:
    url = "http://127.0.0.1:5678/" + link
    result = subprocess.run(["curl", "-sI", "-o", "/dev/null", "-w", "%{http_code}", url],
                          capture_output=True, text=True, timeout=10)
    print(f"  [{result.stdout.strip()}] {link[:80]}...")
