"""Toy two-stage short-video recommender + a "lost focus" session rule.

Stdlib only, deterministic (fixed seed). Run: python3 tiktok-recsys-toy.py

What is grounded in public sources:
  - Stage 1 "retrieval" of a candidate pool, then "prediction -> ranking ->
    similarity check" (TikTok's own recommendation-system explainer).
  - Ranking score in the form reported by the NYT from the internal
    "TikTok Algo 101" doc: Plike*Vlike + Pcomment*Vcomment
    + Eplaytime*Vplaytime + Pplay*Vplay (the doc itself calls it "highly simplified").
  - Updating user state right after feedback (Monolith's idea of online training).

What is NOT verified:
  - LOST_FOCUS_RULE below copies the numbers shown in an unverified Instagram
    reel (play_num 4, max_duration_per_play 2s, total_time_window 6s). It is an
    illustration of that claim, NOT TikTok's code. All weights/models are made up.
"""
import math
import random

rng = random.Random(42)
TOPICS = ["cooking", "dev", "fitness", "music", "travel", "comedy", "pets", "news"]
CREATORS = [f"c{i}" for i in range(12)]

# ---- catalog: 60 videos ---------------------------------------------------
VIDEOS = []
for i in range(60):
    VIDEOS.append({
        "id": f"v{i:02d}",
        "topic": TOPICS[i % len(TOPICS)],
        "creator": rng.choice(CREATORS),
        "duration": rng.choice([8, 15, 22, 30, 45]),
        "quality": round(rng.uniform(-0.5, 0.5), 3),   # item-side signal
        "popularity": rng.random(),
    })

# user interest state (would be learned embeddings in a real system)
user = {"cooking": 1.2, "dev": 1.5, "fitness": -0.4, "music": 0.2,
        "travel": 0.0, "comedy": 0.3, "pets": -0.2, "news": -0.8}
seen = set()

def sigmoid(x):
    return 1 / (1 + math.exp(-x))

# ---- stage 1: retrieval (several cheap retrievers, union) -----------------
def retrieve(k_interest=12, k_popular=4, k_explore=4, explore_only=False):
    pool = [v for v in VIDEOS if v["id"] not in seen]
    by_interest = sorted(pool, key=lambda v: (-user[v["topic"]], v["id"]))[:k_interest]
    by_popular = sorted(pool, key=lambda v: (-v["popularity"], v["id"]))[:k_popular]
    cold = sorted({v["topic"] for v in pool}, key=lambda t: (user[t], t))[:3]
    by_explore = [v for v in pool if v["topic"] in cold][:k_explore * 2]
    if explore_only:
        return {v["id"]: v for v in by_explore + by_popular}.values()
    return {v["id"]: v for v in by_interest + by_popular + by_explore}.values()

# ---- stage 2: multi-objective ranking (Algo 101 form) ---------------------
V = {"like": 1.0, "comment": 2.0, "playtime": 0.05, "play": 0.5}  # made-up weights

def predict(v):
    a = user[v["topic"]] + v["quality"]
    p_like = sigmoid(a - 1.5)
    p_comment = sigmoid(a - 3.0)
    p_play = sigmoid(a + 0.5)                # P(watched past the first seconds)
    e_playtime = v["duration"] * sigmoid(a)  # expected seconds watched
    return p_like, p_comment, e_playtime, p_play

def score(v, explore_bonus=0.0):
    pl, pc, ep, pp = predict(v)
    s = pl * V["like"] + pc * V["comment"] + ep * V["playtime"] + pp * V["play"]
    return s + explore_bonus * (1 - sigmoid(user[v["topic"]]))

# ---- stage 3: re-rank / similarity check ----------------------------------
def rerank(ranked, n, max_per_topic=None):
    out, used = [], {}
    for v in ranked:
        if out and (v["creator"] == out[-1]["creator"] or v["topic"] == out[-1]["topic"]):
            continue  # no two in a row from the same creator or topic
        if max_per_topic and used.get(v["topic"], 0) >= max_per_topic:
            continue
        out.append(v); used[v["topic"]] = used.get(v["topic"], 0) + 1
        if len(out) == n:
            break
    return out

def build_batch(n=6, explore=False):
    cands = list(retrieve(explore_only=explore))
    bonus = 1.5 if explore else 0.0
    ranked = sorted(cands, key=lambda v: (-score(v, bonus), v["id"]))
    return cands, rerank(ranked, n, max_per_topic=1 if explore else None)

# ---- online update (Monolith idea: learn from feedback right away) --------
def update(v, watched):
    frac = min(watched / v["duration"], 1.0)
    user[v["topic"]] += 0.3 * (frac - 0.4)   # >40% watched = positive signal

# ---- "lost focus" rule: ILLUSTRATION OF THE REEL'S CLAIM, NOT VERIFIED -----
LOST_FOCUS_RULE = {"play_num": 4, "max_duration_per_play": 2.0, "total_time_window": 6.0}

def lost_focus(history):
    r = LOST_FOCUS_RULE
    last = history[-r["play_num"]:]
    if len(last) < r["play_num"]:
        return False
    fast = all(w <= r["max_duration_per_play"] for _, w in last)
    span = sum(w for _, w in last)
    return fast and span <= r["total_time_window"]

# ---- simulate one session --------------------------------------------------
def show(title, batch, bonus=0.0):
    print(title)
    for v in batch:
        pl, pc, ep, pp = predict(v)
        print(f"  {v['id']} {v['topic']:<8} {v['creator']:<3} "
              f"Plike={pl:.2f} Pcomment={pc:.2f} Eplay={ep:5.1f}s Pplay={pp:.2f} "
              f"score={score(v):.3f}" + (f" +explore={score(v, bonus):.3f}" if bonus else ""))

cands, batch = build_batch()
print(f"[stage1] retrieved {len(cands)} candidates from {len(VIDEOS)} videos")
show("[batch 1] ranked by Plike*1.0 + Pcomment*2.0 + Eplaytime*0.05 + Pplay*0.5, then re-ranked", batch)

# user watches 2 normally, then gets bored and flicks through the rest
scripted = [None, None, 1.2, 1.8, 1.0, 1.5]
history, t = [], 0.0
for v, w in zip(batch, scripted):
    watched = round(v["duration"] * sigmoid(user[v["topic"]] + v["quality"]), 1) if w is None else w
    seen.add(v["id"]); update(v, watched); history.append((v["id"], watched)); t += watched
    flag = lost_focus(history)
    print(f"  t={t:6.1f}s watched {v['id']} for {watched:4.1f}s  lost_focus={flag}")
    if flag:
        break

if lost_focus(history):
    cands2, batch2 = build_batch(explore=True)
    print(f"[trigger] {LOST_FOCUS_RULE} matched -> push exploration batch "
          f"({len(cands2)} candidates, max 1 per topic)")
    show("[batch 2] exploration / diversity batch (ranked by score + exploration bonus)", batch2, 1.5)
    print("  topics:", sorted({v['topic'] for v in batch2}))
print("[user state after session]", {k: round(x, 2) for k, x in user.items()})
