#!/usr/bin/env python3
"""Merge rank.json (Sensa Watched ranking) with plex-shows.json (Plex library
export) into public/data.json, matched by normalized title (+ year fallback)."""
import json
import os
import re
import unicodedata

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def normalize(title):
    title = unicodedata.normalize("NFKD", title)
    title = "".join(c for c in title if not unicodedata.combining(c))
    title = title.lower()
    title = re.sub(r"[^a-z0-9]+", " ", title)
    return title.strip()


rank = json.load(open(os.path.join(ROOT, "data", "rank.json"), encoding="utf-8"))
plex = json.load(open(os.path.join(ROOT, "data", "plex-shows.json"), encoding="utf-8"))

by_norm_year = {}
by_norm = {}
for p in plex:
    key = (normalize(p["title"]), p["year"])
    by_norm_year[key] = p
    by_norm.setdefault(normalize(p["title"]), p)

result = []
unmatched = []
for r in rank:
    n = normalize(r["title"])
    match = by_norm_year.get((n, r["year"])) or by_norm.get(n)
    if not match:
        unmatched.append(r)
        continue
    result.append({
        "rank": r["rank"],
        "title": match["title"],
        "year": match["year"],
        "seasons": match["seasons"],
        "poster": f"posters/{match['ratingKey']}.jpg",
    })

os.makedirs(os.path.join(ROOT, "public"), exist_ok=True)
with open(os.path.join(ROOT, "public", "data.json"), "w", encoding="utf-8") as f:
    json.dump(result, f, ensure_ascii=False, indent=2)

print(f"matched {len(result)}/{len(rank)}")
if unmatched:
    print("unmatched:")
    for u in unmatched:
        print(f"  #{u['rank']} {u['title']} ({u['year']})")
