#!/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 -c 'import json; d=json.load(open("/var/www/html/IMBD/streamimdb-top.json",encoding="utf-8")); print("SOURCES:",len(d)); [print(x.get("link","")) for x in d]'

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
import 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(item):
    match = re.search(r"(19\d{2}|20\d{2})", item.get("name", ""))
    if match:
        return int(match.group(1))
    return int(item.get("year") or 0)

items.sort(key=year, reverse=True)

p.write_text(
    json.dumps(items, ensure_ascii=False, indent=2) + "\n",
    encoding="utf-8"
)

print("SORTED AUTO:", len(items))
PY2

M3U_COUNT=$(grep -c '^#EXTINF' /var/www/html/IMBD/streamimdb-top.m3u || true)

JSON_COUNT=$(node -e 'const fs=require("fs"); const d=JSON.parse(fs.readFileSync("/var/www/html/IMBD/streamimdb-auto.json","utf8")); console.log(d.length)')

echo "M3U: $M3U_COUNT"
echo "JSON: $JSON_COUNT"
echo "DONE $(date)"
