#!/usr/bin/env python3
"""RVC WebUI：控制台 + 监听端（HTTPS 单端口，页面与音频 WS 同源）
- https://0.0.0.0:8770/          页面
- wss://0.0.0.0:8770/monitor     网页监听（浏览器安全上下文，可枚举/选择输出设备）
- ws  /audio                     可选：走 WS 送音频
- TCP 8765                       游戏主机现有 rvc_client.py 协议（不变）
"""
import os, sys, json, ssl, time, asyncio, threading, traceback
from http import HTTPStatus
import numpy as np
import torch
import websockets

HOME = os.path.expanduser("~")
sys.path.insert(0, HOME)
import rvc_server as core

PAGE = os.path.join(HOME, "rvc_webui.html")
CERT = os.path.join(HOME, "rvcweb", "cert.pem")
KEY = os.path.join(HOME, "rvcweb", "key.pem")
WEB_PORT = int(os.environ.get("RVC_WEB_PORT", "8770"))
NET_SR = core.NET_SR
LOOP = None
MONITORS = set()
STATE = {"pitch": core.PITCH, "formant": 0.0, "index_rate": core.INDEX_RATE,
         "threshold": core.THRESH_DB, "denoise": core.DENOISE, "denoise_mix": core.DENOISE_MIX}


def weights(ext):
    d = os.path.join(HOME, "RVC", "assets", "weights")
    try:
        return sorted(f for f in os.listdir(d) if f.endswith(ext))
    except Exception:
        return []


def apply_settings(m):
    with core.MODEL_LOCK:
        rvc = core.rvc
        if "pitch" in m:
            rvc.f0_up_key = int(m["pitch"]); STATE["pitch"] = int(m["pitch"])
        if "formant" in m:
            rvc.formant_shift = float(m["formant"]); STATE["formant"] = float(m["formant"])
        if "index_rate" in m:
            rvc.index_rate = float(m["index_rate"]); STATE["index_rate"] = float(m["index_rate"])
        if "threshold" in m:
            core.THRESH_DB = float(m["threshold"]); STATE["threshold"] = float(m["threshold"])
        if "denoise" in m:
            core.DENOISE = bool(m["denoise"]); STATE["denoise"] = core.DENOISE
        if "denoise_mix" in m:
            core.DENOISE_MIX = float(m["denoise_mix"]); STATE["denoise_mix"] = core.DENOISE_MIX
        if m.get("index"):
            path = os.path.join(HOME, "RVC", "assets", "weights", m["index"])
            if path != getattr(rvc, "index_path", None) and os.path.isfile(path):
                import faiss
                rvc.index = faiss.read_index(path)
                rvc.big_npy = rvc.index.reconstruct_n(0, rvc.index.ntotal)
                rvc.index_path = path
        if m.get("pth"):
            pth = os.path.join(HOME, "RVC", "assets", "weights", m["pth"])
            if pth != core.PTH:
                if core.STATS["active"] > 0:
                    raise RuntimeError("游戏主机正在发送音频，请先停止再换模型")
                from infer import rtrvc
                import torchaudio.transforms as tat
                new = rtrvc.RVC(int(STATE["pitch"]), float(STATE["formant"]), pth,
                                rvc.index_path, float(STATE["index_rate"]), core.cfg, rvc)
                core.rvc = new
                core.TGT = int(new.tgt_sr)
                core.ZC = max(1, core.TGT // 100)
                core.rs_down = tat.Resample(orig_freq=NET_SR, new_freq=core.TGT, dtype=torch.float32)
                core.rs_up = tat.Resample(orig_freq=core.TGT, new_freq=NET_SR, dtype=torch.float32)
                core.PTH = pth


async def _broadcast(payload):
    for m in list(MONITORS):
        try:
            await m.send(payload)
        except Exception:
            MONITORS.discard(m)


def tap_from_thread(payload):
    if LOOP is None or not MONITORS:
        return
    asyncio.run_coroutine_threadsafe(_broadcast(payload), LOOP)


core.TAP_SINKS.append(tap_from_thread)


async def stats_loop():
    while True:
        await asyncio.sleep(1.0)
        if MONITORS:
            await _broadcast(json.dumps({"type": "stat",
                                         "infer_ms": round(core.STATS["infer_ms"], 1),
                                         "blocks": core.STATS["blocks"],
                                         "active": core.STATS["active"]}))


async def audio_handler(ws, path=None):
    peer = getattr(ws, "remote_address", ("?", 0))[0]
    try:
        hello = await asyncio.wait_for(ws.recv(), timeout=10)
        conf = json.loads(hello) if isinstance(hello, str) else {}
        block_ms = int(conf.get("block_ms", core.BLOCK_MS))
        if any(k in conf for k in ("pitch", "formant", "index_rate", "denoise", "denoise_mix")):
            apply_settings(conf)
        sess = core.StreamSession(block_ms)
        nb = int(NET_SR * block_ms / 1000)
        core.STATS["active"] += 1
        print("[audio] %s connected block=%dms" % (peer, block_ms), flush=True)
        await ws.send(json.dumps({"type": "hello", "tgt_sr": core.TGT, "block_ms": block_ms,
                                  "model": os.path.basename(core.PTH)}))
        while True:
            msg = await ws.recv()
            if isinstance(msg, str):
                m = json.loads(msg)
                if m.get("type") == "settings":
                    try:
                        apply_settings(m); await ws.send(json.dumps({"type": "applied"}))
                    except Exception as e:
                        await ws.send(json.dumps({"type": "error", "msg": str(e)}))
                continue
            x = np.frombuffer(msg, dtype="<i2").astype(np.float32) / 32768.0
            if len(x) < nb:
                x = np.pad(x, (0, nb - len(x)))
            t0 = time.perf_counter()
            y48 = sess.process(x[:nb])
            ms = (time.perf_counter() - t0) * 1000.0
            core.STATS["infer_ms"] = 0.15 * ms + 0.85 * core.STATS["infer_ms"]
            core.STATS["blocks"] += 1
            payload = (np.clip(y48, -1.0, 1.0) * 32767.0).astype("<i2").tobytes()
            await ws.send(payload)
            await _broadcast(payload)
    except Exception:
        traceback.print_exc()
    finally:
        core.STATS["active"] = max(0, core.STATS["active"] - 1)
        print("[audio] %s closed" % peer, flush=True)


async def monitor_handler(ws, path=None):
    MONITORS.add(ws)
    await ws.send(json.dumps({"type": "hello", "tgt_sr": core.TGT, "block_ms": core.BLOCK_MS,
                              "model": os.path.basename(core.PTH),
                              "active": core.STATS["active"], "state": STATE}))
    print("[monitor] %s connected" % getattr(ws, "remote_address", ("?", 0))[0], flush=True)
    try:
        async for msg in ws:
            if isinstance(msg, str):
                m = json.loads(msg)
                if m.get("type") == "settings":
                    try:
                        apply_settings(m)
                        await ws.send(json.dumps({"type": "applied", "state": STATE}))
                    except Exception as e:
                        await ws.send(json.dumps({"type": "error", "msg": str(e)}))
    except websockets.ConnectionClosed:
        pass
    finally:
        MONITORS.discard(ws)
        print("[monitor] closed", flush=True)


async def ws_router(ws, path=None):
    p = path or getattr(ws, "path", "") or ""
    if "monitor" in p:
        await monitor_handler(ws, p)
    else:
        await audio_handler(ws, p)


def http_body(body, ctype="text/html; charset=utf-8", status=HTTPStatus.OK):
    return (status, [("Content-Type", ctype), ("Cache-Control", "no-store"),
                     ("Content-Length", str(len(body)))], body)


def process_request(path, request_headers):
    """非 WebSocket 请求直接在这里回 HTTP（页面 / API）"""
    p = (path or "/").split("?")[0]
    if p.startswith("/monitor") or p.startswith("/audio"):
        return None                      # 交给 WebSocket 握手
    if p in ("/", "/index.html"):
        try:
            return http_body(open(PAGE, "rb").read())
        except FileNotFoundError:
            return http_body(b"<h1>rvc_webui.html missing</h1>")
    if p.startswith("/api/state"):
        return http_body(json.dumps({
            "ok": True, "tgt_sr": core.TGT, "active": core.STATS["active"],
            "block_ms": core.BLOCK_MS, "infer_ms": round(core.STATS["infer_ms"], 1),
            "blocks": core.STATS["blocks"], "monitors": len(MONITORS),
            "state": dict(STATE, pth=core.PTH, index=core.rvc.index_path or ""),
            "pth": weights(".pth"), "index": weights(".index"),
        }, ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8")
    if p.startswith("/api/health"):
        return http_body(b'{"ok":true}', "application/json")
    return http_body(b"not found", "text/plain; charset=utf-8", HTTPStatus.NOT_FOUND)


def serve_all():
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(CERT, KEY)

    async def main():
        global LOOP
        LOOP = asyncio.get_running_loop()
        asyncio.create_task(stats_loop())
        async with websockets.serve(ws_router, "0.0.0.0", WEB_PORT, ssl=ctx,
                                    process_request=process_request,
                                    max_size=2 ** 22, ping_interval=20, ping_timeout=20):
            print("[web] https://0.0.0.0:%d  (page + wss://.../monitor)" % WEB_PORT, flush=True)
            await asyncio.Future()

    asyncio.run(main())


if __name__ == "__main__":
    threading.Thread(target=core.serve_stream, daemon=True).start()
    serve_all()
