#!/usr/bin/python3
import pathlib
import sys
import os

from bs4 import BeautifulSoup
from pywidevine.cdm import Cdm
from pywidevine.device import Device
from pywidevine.pssh import PSSH
import ast
import base64
import json
import requests
from datetime import datetime
from dateutil import parser as date_parser

ACTION = None
STREAMID = None
CHALLENGE = None
CDM = ''
EVENTTYPE=-1



for arg in sys.argv[1:]:
    if '=' in arg:
        key, value = arg.split('=', 1)
        if key == 'action':
            ACTION = value
        elif key == 'id':
            STREAMID = value
        elif key == 'type':
            EVENTTYPE = int(value)
        elif key == 'challenge':
            CHALLENGE = value
            if value == "cert":
                CHALLENGE = "CAQ="
        elif key == 'proxy':
            proxy = value
        elif key == 'bind':
            bind = value
        elif key == 'doh':
            doh = value
        elif key == 'cdm':
            CDM = value


if CHALLENGE == "cert":
    CHALLENGE = "CAQ="


req = requests.Session()


def handle_cdm_external():
    return


def handle_cdm_internal():
    return


def handle_events():
    output = {"Events": []}
    try:

        response = req.get(
            "https://cajablanca.dedyn.io/footballclub/mrpit/cal.json")

        matches = response.json().get("matches", {}).get("primera_federacion", {})
        
        for match in matches:
                name = match.get("name", "")

                numcanal = match.get("canal")
                start_time = match.get("date_start")
                end_time = match.get("date_end")

                # Convert ISO 8601 to Unix timestamp
                start_timestamp = int(date_parser.parse(start_time).timestamp()) if start_time else None
                end_timestamp = int(date_parser.parse(end_time).timestamp()) if end_time else None

                output["Events"].append({
                    "Name": f"Primera RFEF {numcanal} | {name}",
                    "Mode": "live",
                    "SessionManifest": True,
                    "ManifestScript": f"id={numcanal} type=1",
                    "UseCdm": False,
                    "OnDemand": True,
                    "SpeedUp": True,
                    "CdmMode": "internal",
                    "AutoStart": False,
                    "Start": start_timestamp,
                    "End": end_timestamp
                })
        matches = response.json().get("matches", {}).get("segunda_federacion", {})
        
        for match in matches:
                name = match.get("name", "")

                numcanal = match.get("canal")
                start_time = match.get("date_start")
                end_time = match.get("date_end")

                # Convert ISO 8601 to Unix timestamp
                start_timestamp = int(date_parser.parse(start_time).timestamp()) if start_time else None
                end_timestamp = int(date_parser.parse(end_time).timestamp()) if end_time else None

                output["Events"].append({
                    "Name": f"Segunda RFEF {numcanal} | {name}",
                    "Mode": "live",
                    "SessionManifest": True,
                    "ManifestScript": f"id={numcanal} type=2",
                    "UseCdm": False,
                    "OnDemand": True,
                    "SpeedUp": True,
                    "AutoStart": False,
                    "Start": start_timestamp,
                    "End": end_timestamp
                })
        matches = response.json().get("matches", {}).get("tercera_federacion", {})
        
        for match in matches:
                name = match.get("name", "")

                numcanal = match.get("canal")
                start_time = match.get("date_start")
                end_time = match.get("date_end")

                # Convert ISO 8601 to Unix timestamp
                start_timestamp = int(date_parser.parse(start_time).timestamp()) if start_time else None
                end_timestamp = int(date_parser.parse(end_time).timestamp()) if end_time else None

                output["Events"].append({
                    "Name": f"Tercera RFEF {numcanal} | {name}",
                    "Mode": "live",
                    "SessionManifest": True,
                    "ManifestScript": f"id={numcanal} type=3",
                    "UseCdm": False,
                    "OnDemand": True,
                    "SpeedUp": True,
                    "AutoStart": False,
                    "Start": start_timestamp,
                    "End": end_timestamp
                })
        print(json.dumps(output, indent=2))
        sys.exit(0)
    except Exception as e:
        print(f"Error fetching/parsing events: {e}", file=sys.stderr)
        sys.exit(1)


def handle_channels():
    print("Handle channels action handled.")


def handle_heartbeat():
    print("Heartbeat action handled.")


def handle_manifest():
    if not STREAMID:
        print("Missing id", file=sys.stderr)
        sys.exit(1)

    try:
        if EVENTTYPE>0:
            url=f"https://cajablanca.dedyn.io/footballclub/mrpit/{STREAMID}/{EVENTTYPE}/master.m3u8"
            resp = req.get(url)
            m3u8_url = resp.url
            if not m3u8_url or 0 == len(m3u8_url):
                raise Exception("m3u8 URL is missing or empty")
        else:
            url=f"https://cajablanca.dedyn.io/footballclub/mrpit/{STREAMID}/master.m3u8"
 
            # Realizamos una petición GET para seguir la redirección y obtener la URL final
            try:
                resp = req.get(url, allow_redirects=True)
                
                m3u8_url = resp.url
               # print(f"La URL final a la que redirige es: {mpd_url}", file=sys.stderr)
            except Exception as e:
                print(f"Error obteniendo la URL final de redirección: {e}", file=sys.stderr)
                sys.exit(1)
            
    except Exception as e:
        print(f"Error getting m3u8 URL: {e}", file=sys.stderr)
        sys.exit(1)

    

    common_headers = {
        "User-Agent": "Mozilla/5.0 (Linux; Android 15; SM-S926B Build/AP3A.240905.015.A2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/154.0.8025.0 Mobile Safari/537.36"
    }

    result = {
        "ManifestUrl": m3u8_url,
        "Headers": {
            "Manifest": common_headers,
            "Media": common_headers
        }
    }

    print(json.dumps(result))
    sys.exit(0)


def handle_cdm():
    if CDM == "external":
        handle_cdm_external()
    else:
        handle_cdm_internal()


if __name__ == "__main__":
    
    if ACTION == "heartbeat":
        handle_heartbeat()
    elif ACTION == "events":
        handle_events()
    elif ACTION == "channels":
        handle_channels()
    elif ACTION == "manifest":
        handle_manifest()
    elif ACTION == "cdm":
        handle_cdm()
    else:
        print("Invalid or missing action.")
