#!/usr/bin/env python3

import requests
import json
from pathlib import Path

OUTPUT_M3U = Path("/opt/epg/token.txt")

OUTPUT_M3U.parent.mkdir(parents=True, exist_ok=True)

# ============================================================
# SWEET.TV - AuthenticationService/Token.json
# ============================================================

URL = "https://api.sweet.tv/AuthenticationService/Token.json"

# Sem vlož REFRESH TOKEN, nie Analytics access token
#REFRESH_TOKEN = "cff2a17c-4d45-4fe1-8aac-ea9b91d0106f"
REFRESH_TOKEN = "44e3d29c-246b-4513-943e-0c8c44d628ba"
DEVICE_ID = "95aaf03b-f372-49c1-8f90-ea86a23b4687"
#DEVICE_ID = "c41c60af-4248-40f7-a595-77e110dbc57c"

USER_AGENT = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
    "AppleWebKit/537.36 (KHTML, like Gecko) "
    "Chrome/153.0.0.0 Safari/537.36 Edg/153.0.0.0"
)

# ============================================================
# DEVICE
# ============================================================

payload = {
    "device": {
        "type": "DT_Web_Browser",
        "sub_type": "DST_WINDOWS",

        "application": {
            "type": "AT_SWEET_TV_Player"
        },

        "model": USER_AGENT,

        "firmware": {
            "versionCode": 1,
            "versionString": "9.0.96"
        },

        "uuid": DEVICE_ID,

        "screen_info": {
            "width": 1536,
            "height": 864,
            "aspectRatio": 6
        },

        "supported_drm": {
            "widevine_modular": True
        },

        "drm_info": {
            "widevine_info": {
                "security_level": "SECURITY_LEVEL_L3",
                "system_id": None,
                "version": None
            }
        }
    },

    "refresh_token": REFRESH_TOKEN
}

# ============================================================
# HEADERS
# ============================================================

headers = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Language": "sk,cs,hu,pl,en",
    "Content-Type": "application/json",
    "Origin": "https://sweet.tv",
    "Referer": "https://sweet.tv/",
    "User-Agent": USER_AGENT
}

# ============================================================
# REQUEST
# ============================================================

print("=" * 60)
print("SWEET.TV AuthenticationService / Token")
print("=" * 60)
print()

print("URL:", URL)
print("DEVICE:", DEVICE_ID)
print("FIRMWARE: 9.0.96")
print()

print("POSIELAM REQUEST...")
print()

try:

    r = requests.post(
        URL,
        headers=headers,
        json=payload,
        timeout=20
    )

except requests.RequestException as e:

    print("REQUEST ERROR:")
    print(type(e).__name__, e)
    raise SystemExit


print("HTTP:", r.status_code)
print()

# ============================================================
# RESPONSE
# ============================================================

try:

    data = r.json()

except Exception:

    print("RESPONSE NIE JE JSON:")
    print(r.text)
    raise SystemExit


print("RESPONSE:")
print(json.dumps(data, indent=4, ensure_ascii=False))

# ============================================================
# TOKEN
# ============================================================

access_token = data.get("access_token")

if access_token:

    with open("/opt/epg/token.txt", "w", encoding="utf-8") as f:
        f.write(access_token)

    print()
    print("ACCESS TOKEN uložený do:")
    print("/opt/epg/token.txt")

else:

    print()
    print("ACCESS TOKEN NEBOL NÁJDENÝ")