#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 独立子进程：内嵌浏览器加载网页登录地址，轮询 hash 是否含 login= 后写入标记文件。
# 若未安装 webview 库则进程以码 2 退出（主程序改用系统浏览器 + 手动检测）。

from __future__ import annotations

import pathlib
import sys
import threading
import time


def main() -> None:
    if len(sys.argv) < 3:
        sys.exit(1)
    url = sys.argv[1]
    marker = pathlib.Path(sys.argv[2])
    try:
        import webview
    except ImportError:
        sys.exit(2)
    marker.parent.mkdir(parents=True, exist_ok=True)
    if marker.exists():
        marker.unlink()

    def watch() -> None:
        time.sleep(0.8)
        while True:
            try:
                wins = webview.windows
                if not wins:
                    break
                w = wins[0]
                h = w.evaluate_js("window.location.hash || ''") or ""
                if "login=" in h:
                    marker.write_text("ok", encoding="utf-8")
                    try:
                        w.destroy()
                    except Exception:
                        pass
                    break
            except Exception:
                pass
            time.sleep(0.45)

    def started() -> None:
        threading.Thread(target=watch, daemon=True).start()

    webview.create_window("Web登录", url, width=800, height=800)
    webview.start(started)


if __name__ == "__main__":
    main()
