"""
Date: 16th/July/2026
Created by: Jap-Slappa 

Trakt History Fetcher--v1.0 (For Anime)
Customised By: Jap-Slappa
Base Code By Gemini

Completed: Not/Not_Yet/2026
"""

# import PySimpleGUI as sg
import traceback
# import logging
import sys
import time
from pathlib import Path

# Tell Python to look in your C-Drive helper folder
# Use raw strings (r"...") to handle Windows backslashes properly
# sys.path.append(r"C:\My_Python_Helper_Modules")  # OG Code
sys.path.append(r"\\DS918-ms\usbshare1\My_Python_Helper_Modules")
import Get_Date_and_Time__v1 as Get_Date_and_Time
# Get_Date_and_Time.Fav_Day_date_and_time_string()

from trakt import Trakt
from datetime import datetime, timedelta, timezone

# --- CONFIGURATION ---
# Replace these with your details from https://trakt.tv/oauth/applications
CLIENT_ID = 'c445854294b2d9105cf1ce8056ddbff01c19c5464cf1641df3343737be7ff9ce'
CLIENT_SECRET = '7011753aa24821ea65110ab43e0d94152df488c3966b20d857b283325dc5f8d6'

def fetch_recent_history():
    Trakt.configuration.defaults.client(id=CLIENT_ID, secret=CLIENT_SECRET)
    
    # 3. Calculate threshold (Last 24 hours)
    one_day_ago = datetime.now(timezone.utc) - timedelta(days=1)
    
    print(f"Fetching history since: {one_day_ago.strftime('%Y-%m-%d %H:%M:%S')}")
    print("-" * 50)

    try:
        # The 'get' method on the history endpoint does not support 'limit'.
        # We retrieve the history and filter it in Python.
        history = Trakt['users/me/history'].get(media='episodes')

        count = 0
        for entry in history:
            # entry.watched_at is provided by the library
            watched_at = entry.watched_at
            
            # Ensure it is timezone-aware and compare
            if watched_at.replace(tzinfo=timezone.utc) > one_day_ago:
                show = entry.show.title
                episode_title = entry.episode.title
                season = entry.episode.season
                ep_num = entry.episode.number
                
                print(f"[{watched_at.strftime('%Y-%m-%d %H:%M:%S')}] {show} - S{season:02d}E{ep_num:02d} - {episode_title}")
                count += 1
                
        if count == 0:
            print("No episodes found in the last 24 hours.")
        else:
            print(f"\nTotal episodes found: {count}")
            
    except Exception as e:
        print(f"Error fetching history: {e}")
        print("Note: If this is an authentication error, you may need to perform the OAuth device flow once.")

def outh_Trakt():
    Trakt.configuration.defaults.client(id=CLIENT_ID, secret=CLIENT_SECRET)
    device = Trakt['oauth/device'].code()
    print(f"Go to {device['verification_url']} and enter code: {device['user_code']}")
    token = Trakt['oauth/device'].poll(device=device)
    # # This will save your token automatically

if __name__ == "__main__":
    # outh_Trakt()
    fetch_recent_history()


### Important Setup Note for `trakt.py` v4.x
# If this script throws an `OAuthException` or `Unauthorized` error, it means you haven't # linked your app yet. 
# `trakt.py` (v4.4.0) usually expects you to have an `oauth.json` # file in your directory or environment.
# 
# **How to authenticate if you get an error:**
# Run this tiny snippet once to perform the device authorization:
# ```python
# from trakt import Trakt
# Trakt.configuration.defaults.client(id=CLIENT_ID, secret=CLIENT_SECRET)
# device = Trakt['oauth/device'].code()
# print(f"Go to {device['verification_url']} and enter code: {device['user_code']}")
# token = Trakt['oauth/device'].poll(device=device)
# # This will save your token automatically
# ```
# 
# Once that is done, the main script above will work perfectly every time you run it!

