#!/bin/bash
set -e
cd /var/www/html/IMBD || exit 1

echo "START $(date)"

node /var/www/html/IMBD/build-streamimdb-top-json.js

python3 - <<'PYADD'
import json
from pathlib import Path

p = Path("/var/www/html/IMBD/streamimdb-top.json")
items = json.loads(p.read_text(encoding="utf-8"))

manual = [
  {"name":"Kickboxer 1989","year":1989,"code":"tt0097659","link":"https://streamimdb.ru/embed/movie/tt0097659","logo":""},
  {"name":"Hard Target 1993","year":1993,"code":"tt0107076","link":"https://streamimdb.ru/embed/movie/tt0107076","logo":""},
  {"name":"Double Impact 1991","year":1991,"code":"tt0101764","link":"https://streamimdb.ru/embed/movie/tt0101764","logo":""},
  {"name":"Lionheart 1990","year":1990,"code":"tt0100029","link":"https://streamimdb.ru/embed/movie/tt0100029","logo":""},
  {"name":"Cyborg 1989","year":1989,"code":"tt0097138","link":"https://streamimdb.ru/embed/movie/tt0097138","logo":""},
  {"name":"Death Warrant 1990","year":1990,"code":"tt0099385","link":"https://streamimdb.ru/embed/movie/tt0099385","logo":""},
  {"name":"Sudden Death 1995","year":1995,"code":"tt0114576","link":"https://streamimdb.ru/embed/movie/tt0114576","logo":""},
  {"name":"Maximum Risk 1996","year":1996,"code":"tt0117011","link":"https://streamimdb.ru/embed/movie/tt0117011","logo":""}
]

seen = {x.get("code") for x in items}
added = 0
for m in manual:
    if m["code"] not in seen:
        items.append(m)
        added += 1

items.sort(key=lambda x: int(x.get("year") or 0), reverse=True)
p.write_text(json.dumps(items, ensure_ascii=False, indent=2), encoding="utf-8")
print("MANUAL ADDED:", added)
PYADD

python3 /var/www/html/IMBD/build-streamimdb-top-m3u.py
python3 /var/www/html/IMBD/m3u-to-streamimdb-auto-json.py

python3 - <<'PY2'
import json, re
from pathlib import Path

p = Path("/var/www/html/IMBD/streamimdb-auto.json")
items = json.loads(p.read_text(encoding="utf-8"))

def year(x):
    m = re.search(r"(19\d{2}|20\d{2})", x.get("name",""))
    return int(m.group(1)) if m else int(x.get("year") or 0)

items.sort(key=year, reverse=True)
p.write_text(json.dumps(items, ensure_ascii=False, indent=2), encoding="utf-8")
print("SORTED AUTO:", len(items))
PY2

echo "M3U: $(grep -c '^#EXTINF' /var/www/html/IMBD/streamimdb-top.m3u)"
echo "JSON: $(node -e "console.log(JSON.parse(require('fs').readFileSync('/var/www/html/IMBD/streamimdb-auto.json','utf8')).length)")"
echo "DONE $(date)"