#!/usr/bin/env python3
"""區網 HTTPS 靜態伺服器（手機 Chrome 需要 https 才能 WebRTC 連線）。"""
from __future__ import annotations
import argparse
import http.server
import os
import socketserver
import ssl
import subprocess
import sys
from pathlib import Path

WEB = Path(__file__).resolve().parent
CERT = WEB / "cert.pem"
KEY = WEB / "key.pem"


def lan_ip() -> str:
    try:
        out = subprocess.check_output(["hostname", "-I"], text=True).strip()
        return out.split()[0] if out else "127.0.0.1"
    except Exception:
        return "127.0.0.1"


def ensure_cert(ip: str) -> None:
    if CERT.exists() and KEY.exists():
        return
    print(f"產生自簽憑證（含 IP {ip}）…")
    subprocess.check_call([
        "openssl", "req", "-x509", "-newkey", "rsa:2048",
        "-keyout", str(KEY), "-out", str(CERT),
        "-days", "365", "-nodes", "-subj", "/CN=Pich2Pich",
        "-addext", f"subjectAltName=IP:{ip},IP:127.0.0.1,DNS:localhost",
    ])


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("--port", type=int, default=8000)
    args = p.parse_args()
    ip = lan_ip()
    ensure_cert(ip)
    os.chdir(WEB)
    handler = http.server.SimpleHTTPRequestHandler

    class ReuseServer(socketserver.TCPServer):
        allow_reuse_address = True

    httpd = ReuseServer(("0.0.0.0", args.port), handler)
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(str(CERT), str(KEY))
    httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
    print("=" * 44)
    print(" Pich2Pich HTTPS（手機 Chrome 請用這個）")
    print(f"  本機：     https://localhost:{args.port}")
    print(f"  手機 Chrome：https://{ip}:{args.port}")
    print("")
    print("  第一次手機會警告「不安全」→ 進階 → 仍要繼續")
    print("  連線：聊天與連線 → 代碼互貼 或 輸入對方代碼")
    print("  停止：Ctrl+C")
    print("=" * 44)
    httpd.serve_forever()


if __name__ == "__main__":
    main()
