#!/usr/local/bin/python

import json
from datetime import datetime, timedelta
# python -m ensurepip
# python -m pip install requests
import requests

current_time = datetime.now()
start_day_query = current_time.strftime('%Y-%m-%d')
end_day_query = (current_time + timedelta(days=7)).strftime('%Y-%m-%d')


# Define the URL
url = "https://epg-api.discovery.bellmedia.ca/graphql"

# Define the payload for the POST request
payload = "{\"query\":\"query getEvents {getEvents(channelNames:[\\\"TSN1\\\",\\\"TSN2\\\",\\\"TSN3\\\",\\\"TSN4\\\",\\\"TSN5\\\",\\\"TSN+\\\"] channelGroup:\\\"TSN+\\\", startTimeUtc:\\\"" + start_day_query + "T00:00:00-07:00\\\", endTime: \\\"" + end_day_query + "T23:59:59-07:00\\\") {channelName title startTimeUtc startTimeLocal endTime duration shortDescription axisStream sportName}}\",\"variables\":null}"

# Define the headers for the POST request
headers = {
   "Content-Type": "application/json",
   "x-api-key": "da2-tfunm6yfqnfuvla4jynnrbvlye"
}

# Make the POST request
response = requests.post(url, data=payload, headers=headers)

# Save the response to a file
with open("tsn.txt", "w") as file:
   file.write(response.text)

# print("The response has been saved to tsn.txt")


# Read the JSON data from the file named tsn.txt
with open('tsn.txt', 'r') as file:
   json_data = file.read()

data = json.loads(json_data)
events = data['data']['getEvents']

# Filter events where the channel starts with TSN+
# filtered_events = [event for event in events if event['channelName'].startswith('TSN+')]
filtered_events = [event for event in events if event['channelName'].startswith('TSN')]

# Sort the filtered events by time, then by channel
filtered_events.sort(key=lambda x: (x['startTimeLocal'], x['channelName']))

# Print column labels with specified widths
print(f"{'Time':<25} {'Title':<60} {'Channel':<10}")

previous_day = None

# Print each event's details with specified widths and truncate title at 60 characters
for event in filtered_events:
   start_time = datetime.fromisoformat(event['startTimeLocal'].replace('Z', '+00:00'))
   adjusted_time = start_time - timedelta(hours=8)
   formatted_time = adjusted_time.strftime('%a %b %dth %I:%M%p')
   truncated_title = (event['title'][:57] + '...') if len(event['title']) > 60 else event['title']
   channel_name = event['channelName'] # .split('+')[0] + '+'

   # Check if the current event is on the next day compared to the previous event
   if previous_day and adjusted_time.date() > previous_day:
       print()  # Print a blank line

   print(f"{formatted_time:<25} {truncated_title:<60} {channel_name:<10}")

   # Update the previous_day to the current event's day
   previous_day = adjusted_time.date()