save_dir = "docs/webpages"           # 页面保存目录
site_map_file = "docs/webpages/site_map.yaml"  # 页面信息保存文件

import ctypes
import os
import tkinter as tk
from tkinter import messagebox
from urllib.parse import urlparse, urlunparse
import yaml

from bs4 import BeautifulSoup
from selenium import webdriver


os.makedirs(save_dir, exist_ok=True)


def enable_hdpi_awareness():
    if os.name != "nt":
        return

    try:
        ctypes.windll.user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4))
        return
    except Exception:
        pass

    try:
        ctypes.windll.shcore.SetProcessDpiAwareness(2)
        return
    except Exception:
        pass

    try:
        ctypes.windll.user32.SetProcessDPIAware()
    except Exception:
        pass


def apply_tk_scaling(window):
    try:
        window.tk.call("tk", "scaling", window.winfo_fpixels("1i") / 72)
    except tk.TclError:
        pass

def get_urlpath(url):
    parsed = urlparse(url)
    path = parsed.path or "/"
    return urlunparse(("", "", path, parsed.params, parsed.query, parsed.fragment))


def configure_browser_options(options):
    prefs = {
        "credentials_enable_service": False,
        "profile.password_manager_enabled": False,
        "profile.password_manager_leak_detection": False,
    }
    options.add_experimental_option("excludeSwitches", ["enable-logging"])
    options.add_experimental_option("prefs", prefs)
    options.add_argument("--disable-features=PasswordLeakDetection")
    return options


def refresh_url_info():
    try:
        status_var.set(f"保存目录：{save_dir}")
    except Exception as exc:
        status_var.set(f"读取当前页面地址失败：{exc}")


def save_current_page():
    file_name = file_name_var.get().strip()
    if not file_name:
        messagebox.showwarning("缺少文件名", "请输入文件名")
        return

    try:
        current_url = driver.current_url
        urlpath = get_urlpath(current_url)
        html = driver.page_source

        soup = BeautifulSoup(html, "lxml")
        pretty_html = soup.prettify()

        html_file_path = os.path.join(save_dir, file_name + ".html")
        with open(html_file_path, "w", encoding="utf-8") as f:
            f.write(pretty_html)

        site_map = {}
        if os.path.exists(site_map_file):
            try:
                with open(site_map_file, "r", encoding="utf-8") as f:
                    site_map = yaml.safe_load(f) or {}
            except Exception:
                site_map = {}

        site_map[file_name] = {
            "urlpath": urlpath,
            "saved_html": os.path.relpath(html_file_path, save_dir).replace("\\", "/")
        }

        with open(site_map_file, "w", encoding="utf-8") as f:
            yaml.safe_dump(site_map, f, allow_unicode=True, default_flow_style=False, sort_keys=False)

        status_var.set(f"已保存：{html_file_path} 和 {site_map_file}")
        # messagebox.showinfo("保存完成", f"HTML 已保存为 {html_file_path}")
    except Exception as exc:
        messagebox.showerror("保存失败", str(exc))
        status_var.set(f"保存失败：{exc}")


def on_close():
    try:        
        root.destroy()
        driver.quit()
    finally:
        os._exit(0)


enable_hdpi_awareness()
root = tk.Tk()
apply_tk_scaling(root)
root.title("下载当前页面 HTML")
root.columnconfigure(1, weight=1)

file_name_var = tk.StringVar()
status_var = tk.StringVar()

tk.Label(root, text="文件名：").grid(row=0, column=0, padx=8, pady=(10, 4), sticky="e")
file_name_entry = tk.Entry(root, textvariable=file_name_var, width=40)
file_name_entry.grid(row=0, column=1, padx=8, pady=(10, 4), sticky="ew")
tk.Button(root, text="下载当前页面 HTML", command=save_current_page).grid(row=0, column=2, padx=8, pady=(10, 4))

tk.Label(root, textvariable=status_var, anchor="w").grid(row=1, column=0, columnspan=3, padx=8, pady=(4, 10), sticky="ew")

root.bind("<Return>", lambda _event: save_current_page())
root.protocol("WM_DELETE_WINDOW", on_close)


options = configure_browser_options(webdriver.EdgeOptions())
driver = webdriver.Edge(options=options)

refresh_url_info()
file_name_entry.focus()



root.mainloop()
