"""按 IP 统计下载并发（租约估算），租约存数据库 dl_lease 表。

真实文件字节由 nginx X-Accel-Redirect 直出，应用看不到传输进度与结束时刻，
因此采用租约估算：每次 /download 请求登记一个 90 秒到期的租约行。
多线程下载器（Motrix 等）每开一条线程就产生一次新请求，
线程结束后租约自然过期——计数会比真实并发晚释放约 1~2 分钟，属保守偏差。
租约存库而非内存：uvicorn 多 worker 各自内存独立，会导致限额口径翻倍、
活跃面板只能看到部分数据。超限后的限速由响应头 X-Accel-Limit-Rate 交给 nginx 执行。
"""
import time

LEASE_TTL = 90  # 秒


def admit(conn, ip, label=""):
    """登记一次下载请求，返回该 IP 当前并发数（含本次）"""
    now = int(time.time())
    conn.execute("DELETE FROM dl_lease WHERE expires < ?", (now,))
    conn.execute("INSERT INTO dl_lease (ip, label, expires) VALUES (?,?,?)",
                 (ip, (label or "")[:120], now + LEASE_TTL))
    row = conn.execute(
        "SELECT COUNT(*) AS c FROM dl_lease WHERE ip = ? AND expires >= ?", (ip, now)
    ).fetchone()
    return row["c"]


def snapshot(conn):
    """当前活跃下载视图：[{ip, conns, files}]，按并发数降序"""
    now = int(time.time())
    conn.execute("DELETE FROM dl_lease WHERE expires < ?", (now,))
    rows = conn.execute(
        "SELECT ip, label FROM dl_lease WHERE expires >= ? ORDER BY id DESC", (now,)
    ).fetchall()
    out, seen = [], {}
    for r in rows:
        ip = r["ip"]
        if ip not in seen:
            seen[ip] = {"ip": ip, "conns": 0, "files": []}
            out.append(seen[ip])
        e = seen[ip]
        e["conns"] += 1
        if r["label"] and r["label"] not in e["files"] and len(e["files"]) < 6:
            e["files"].append(r["label"])
    out.sort(key=lambda x: -x["conns"])
    return out
