import os
import time
import json
import asyncio
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# Assuming welcome_banner.py provides a function called display_welcome_banner
try:
    from .welcome_banner import display_welcome_banner  # Relative import for package structure
except ImportError:
    def display_welcome_banner():
        print("Welcome banner displayed (dummy function - welcome_banner.py not found).")

# Configure logging
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

HANDOFF_FILE = "HANDOFF.md"  # Define the file we're watching for
SESSIONS_LOG_FILE = "data/sessions.jsonl"  # Define the session log file

class HandoffHandler(FileSystemEventHandler):
    """
    Handles file system events, specifically creation/modification of HANDOFF.md.
    """

    def on_modified(self, event):
        if event.is_directory:
            return
        if event.src_path.endswith(HANDOFF_FILE):
            self.process_handoff()

    def on_created(self, event):
        if event.is_directory:
            return
        if event.src_path.endswith(HANDOFF_FILE):
            self.process_handoff()

    def process_handoff(self):
        """
        Processes the HANDOFF.md file, logs the session, and triggers the welcome banner.
        """
        try:
            # Inferred agent type can be improved by reading the HANDOFF.md content
            agent_type = "InferredAgent" # Default if we cannot determine agent type.
            try:
                with open(HANDOFF_FILE, 'r') as f:
                    content = f.read()
                    if "GPT" in content:
                        agent_type = "GPTAgent"
                    elif "Human" in content:
                        agent_type = "HumanAgent"
            except FileNotFoundError:
                logging.warning(f"{HANDOFF_FILE} not found while processing handoff.")
                return


            session_data = {
                "timestamp": time.time(),
                "agent_type": agent_type
            }

            self.log_session(session_data)
            asyncio.create_task(self.trigger_welcome())  # Start welcome banner asynchronously

        except Exception as e:
            logging.error(f"Error processing handoff: {e}")

    def log_session(self, session_data):
        """
        Logs the session data to the sessions log file.
        """
        try:
            os.makedirs(os.path.dirname(SESSIONS_LOG_FILE), exist_ok=True) # ensure directory exists
            with open(SESSIONS_LOG_FILE, "a") as f:
                f.write(json.dumps(session_data) + "\n")
            logging.info(f"Session logged: {session_data}")
        except Exception as e:
            logging.error(f"Error logging session: {e}")

    async def trigger_welcome(self):
        """
        Triggers the welcome banner display (non-blocking).
        """
        try:
            display_welcome_banner()
        except Exception as e:
            logging.error(f"Error displaying welcome banner: {e}")


async def main():
    """
    Main function to start the session detector.
    """
    event_handler = HandoffHandler()
    observer = Observer()
    observer.schedule(event_handler, path='.', recursive=False)  # Watch the current directory
    observer.start()

    try:
        while True:
            await asyncio.sleep(1)  # Keep the script running
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == "__main__":
    asyncio.run(main())