"""
* If there is a new message, it'll run the read chat function. If that runs, we check to see if source is active. If it is active, we do nothing, if it's not,
* we activate it and reset the timer (for both scenerios)
*
* If the Add_Timer function is funning the bottom half, that means 30 seconds have passed without any new activity. Check to see if source is active, if so,
* we deactivate it. If not, we do nothing. We also need to reset the timer for both scenerios
"""

import obspython as obs
import socket

server = "irc.chat.twitch.tv"
port = 6667
nickname = "justinfan12345"   # anonymous login
token = "SCHMOOPIIE"
channel = "#" # Edit this to include your Twitch name (Keep the "#") E.X: "#malik4033"

irc = None

name_of_source = "Test" # This will be your source name. 

timer_variable = 0

connection = 0

def deactivate_source(source_name):
    if obs.obs_frontend_streaming_active():
        # Get the current scene
        current_scene_source = obs.obs_frontend_get_current_scene()
        if current_scene_source is None:
            return
    
        current_scene = obs.obs_scene_from_source(current_scene_source)

        # Find the scene item for this source
        scene_item = obs.obs_scene_find_source(current_scene, source_name)
        if scene_item is not None:
            obs.obs_sceneitem_set_visible(scene_item, False)
        
        # Release reference
        obs.obs_source_release(current_scene_source)

def add_timer(): # This adds 5 seconds to the variable every 5 seconds
    if obs.obs_frontend_streaming_active():
        global timer_variable
        timer_variable += 5 # adds 5 seconds every 5 seconds

        if (timer_variable == 60): # 30 seconds passed
            source_active = is_source_active(name_of_source)

            if source_active: # Source is active with no new message. Disable it and reset timer
                deactivate_source(name_of_source)
                print("Disabling Source")
                timer_variable = 0
            elif source_active == False:
                # No new message and source is already disabled. Do nothing but reset timer
                timer_variable = 0
                print("Source already not active, resetting timer")


def is_source_active(source_name: str) -> bool:
    source = obs.obs_get_source_by_name(source_name)
    if source is not None:
        active = obs.obs_source_active(source)   # returns True/False
        obs.obs_source_release(source)
        return active
    return False

def connect():
    global irc, connection
    try:
        if connection == 0:
            irc = socket.socket()
            irc.connect((server, port))
            irc.setblocking(False)
            irc.send(f"PASS {token}\r\n".encode("utf-8"))
            irc.send(f"NICK {nickname}\r\n".encode("utf-8"))
            irc.send(f"JOIN {channel}\r\n".encode("utf-8"))
            print("✅ Connected to Twitch chat")
            connection = 1
    except Exception as e:
        print("❌ Connect error:", e)
        irc = None
        connection = 0
    else:
        connection = 0


def activate_source(source_name):
    # Get the current scene
    current_scene_source = obs.obs_frontend_get_current_scene()
    if current_scene_source is None:
        return
    
    current_scene = obs.obs_scene_from_source(current_scene_source)

    # Find the scene item for this source
    scene_item = obs.obs_scene_find_source(current_scene, source_name)
    if scene_item is not None:
        obs.obs_sceneitem_set_visible(scene_item, True)
    
    # Release reference
    obs.obs_source_release(current_scene_source)

def poll_chat():
    global irc, timer_variable

    if irc is None:
        connect()
        return

    try:
        data = irc.recv(1024).decode("utf-8")

        if not data:
            print("⚠️ Disconnected from Twitch (no data). Reconnecting...")
            try:
                irc.close()
            except:
                pass
            irc = None   # force reconnect next tick
            connection = 0
            return

        if data.startswith("PING"):
            irc.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
            return

        parts = data.split(":", 2)
        if len(parts) >= 3:
            username = parts[1].split("!")[0]
            message = parts[2].strip()
            # Checking to see if source is active
            source_active = is_source_active(name_of_source)

            # If this runs, that means it found a message
            if source_active: # This means new message and source is already active
                #Keep source active and reset timer
                timer_variable = 0
                print("Source Already Active")
            elif source_active == False: # Source is not active, and we received a new message. Activate source
                activate_source(name_of_source) # Source is active
                timer_variable = 0
                print("Activating Source")

    except BlockingIOError:
        # no new message, do nothing
        pass

    except Exception as e:
        print("⚠️ Socket error:", e)
        try:
            irc.close()
        except:
            pass
        irc = None  # reconnect next tick

def script_load(settings):
    connect()

def script_tick(seconds):
    poll_chat()

obs.timer_add(add_timer, 5000)