import requests
import json
import os
import time
import hashlib

# Configurações
CACHE_DIR = 'cache'
if not os.path.exists(CACHE_DIR):
    os.makedirs(CACHE_DIR)

AUTH_FILES = ['authh', 'authhh']
TOKEN_DURATION = 180  # 3 minutos (igual ao seu PHP)

def get_auth_token():
    for auth_file in AUTH_FILES:
        if os.path.exists(auth_file):
            with open(auth_file, 'r') as f:
                return f.read().strip()
    return None

def get_manifest_url(cid):
    cache_file = os.path.join(CACHE_DIR, hashlib.md5(cid.encode()).hexdigest())
    
    # 1. Verificação de Cache
    if os.path.exists(cache_file):
        if (time.time() - os.path.getmtime(cache_file)) < TOKEN_DURATION:
            with open(cache_file, 'r') as f:
                data = f.read().split('|')
                if len(data) >= 1:
                    return data[0] # Retorna a URL do cache

    # 2. Requisição de Novo Token
    url_api = 'https://api.directvgo.com/entitlement/v3/playback/token/authorizer'
    auth = get_auth_token()
    
    if not auth:
        return "Erro: Arquivo authh não encontrado."

    headers = {
        'x-client-version': '3.18.0',
        'x-environment': 'prd',
        'user-agent': 'Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36',
        'content-type': 'application/json',
        'accept': 'application/json, text/plain, */*',
        'x-client-id': 'Android', # Mantendo seu padrão Android
        'x-app': 'skymais',
        'origin': 'https://www.skymais.com.br',
        'referer': 'https://www.skymais.com.br/',
        'Authorization': f'Bearer {auth}'
    }

    payload = {
        'delay': 0,
        'mobileNetwork': True,
        'isLive': True,
        'contentId': cid
    }

    try:
        response = requests.post(url_api, headers=headers, json=payload, verify=False)
        if response.status_code == 200:
            res_data = response.json()
            # Pega a URL original da Sky sem limpar nada
            url_dash = res_data.get('manifest', {}).get('dash', {}).get('primary', '')
            
            if url_dash:
                # Salva no cache para evitar requisições repetidas
                with open(cache_file, 'w') as f:
                    f.write(f"{url_dash}")
                return url_dash
        else:
            return f"Erro na API: {response.status_code}"
    except Exception as e:
        return f"Erro de conexão: {str(e)}"

# Exemplo de Uso:
canal_id = "CH0100000000082"
url_final = get_manifest_url(canal_id)

print(f"\n--- URL DIRETA DA SKY PARA O CANAL {canal_id} ---")
print(url_final)