import requests
import time
import urllib3
import json
from urllib.parse import urlparse, urlunparse

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

CONFIG_ARQUIVO = "channels.json"   # lista de canais
TOKEN_ARQUIVO = "token.txt"        # arquivo com o Bearer token
ARQUIVO_SAIDA = "streams.json"     # saída com links
INTERVALO = 7200                   # tempo entre execuções (segundos)

FINAL_FIXO_S2 = "s2/playlist_nova-b.m3u8"
FINAL_FIXO_S1 = "s1/playlist_nova-a.m3u8"

def carregar_canais():
    with open(CONFIG_ARQUIVO, "r", encoding="utf-8") as f:
        return json.load(f)

def carregar_token():
    try:
        with open(TOKEN_ARQUIVO, "r", encoding="utf-8") as f:
            return f.read().strip()
    except Exception as e:
        print(f"[ERRO] Não conseguiu carregar token: {e}")
        return None

def pegar_hls(url, token, final_fixo):
    try:
        headers = {
            "Accept": "application/json, text/plain, */*",
            "User-Agent": "Bandplay/1.0.0 CFNetwork/3826.600.41 Darwin/24.6.0",
            "Authorization": f"Bearer {token}",
            "Accept-Language": "pt-BR,pt;q=0.9"
        }
        r = requests.get(url, headers=headers, timeout=10, verify=False)
        r.raise_for_status()
        dados = r.json()
        hls_link = dados.get("assets", {}).get("hls")
        if hls_link:
            parsed = urlparse(hls_link)
            partes = parsed.path.split('/')
            try:
                idx = partes.index('live')
                live_id_path = '/'.join(partes[:idx+2])  # /live/<id>
            except ValueError:
                live_id_path = parsed.path
            novo_path = f"{live_id_path}/{final_fixo}"
            hls_link = urlunparse(parsed._replace(path=novo_path))
        return hls_link
    except Exception as e:
        print(f"[ERRO] Não conseguiu pegar HLS: {e}")
        return None

def salvar_json(dados):
    with open(ARQUIVO_SAIDA, "w", encoding="utf-8") as f:
        json.dump(dados, f, indent=2, ensure_ascii=False)
    print(f"[OK] Todos os links salvos em {ARQUIVO_SAIDA}")

def main():
    while True:
        token = carregar_token()
        if not token:
            print("[ERRO] Token não encontrado, aguardando...")
            time.sleep(INTERVALO)
            continue

        canais = carregar_canais()
        resultado = {}

        for canal_id, info in canais.items():
            nome = info.get("nome", canal_id)
            url_api = info.get("url")

            # --- link com s2 ---
            hls_s2 = pegar_hls(url_api, token, FINAL_FIXO_S2)
            if hls_s2:
                resultado[canal_id] = hls_s2
                print(f"[OK] {nome} ({canal_id}): link HLS S2 capturado")
            else:
                print(f"[ERRO] {nome} ({canal_id}): não conseguiu pegar HLS S2")

            # --- link com s1 ---
            hls_s1 = pegar_hls(url_api, token, FINAL_FIXO_S1)
            if hls_s1:
                novo_id = canal_id.replace("ch", "id")  # ch1 -> id1
                resultado[novo_id] = hls_s1
                print(f"[OK] {nome} ({novo_id}): link HLS S1 capturado")
            else:
                print(f"[ERRO] {nome} ({canal_id}): não conseguiu pegar HLS S1")

        salvar_json(resultado)
        time.sleep(INTERVALO)

if __name__ == "__main__":
    main()
