# hiveos/session_manager.py

import uuid
from threading import RLock
from hiveos.core import Core
import time

class SessionManager:
    def __init__(self):
        self._lock = RLock()
        self.sessions = {}
        self.active_sessions = {}  # 🔄 NEW: {user_id: session_id}
        self.active_session_id = None
        self._label_counter = 1
        self.gc_interval = 30  # seconds between GC sweeps
        self.start_gc_loop()



    def start_gc_loop(self):
        from threading import Thread

        def gc_loop():
            while True:
                time.sleep(self.gc_interval)
                with self._lock:
                    sessions_snapshot = list(self.sessions.items())
                for sid, session in sessions_snapshot:
                    core = session.get("core")
                    if core and self.should_cleanup(core):
                        print(f"[GC] Cleaning up expired session {sid}")
                        try:
                            core.teardown()
                        except Exception as e:
                            print(f"[GC] Error tearing down session {sid}: {e}")
                        with self._lock:
                            self.sessions.pop(sid, None)
                            if sid == self.active_session_id:
                                self.active_session_id = next(iter(self.sessions), None)

        Thread(target=gc_loop, daemon=True).start()


    def create_session(self, label=None, user_id=None):
        session_id = str(uuid.uuid4())
        with self._lock:
            if not label:
                label = f"Session {self._label_counter}"
                self._label_counter += 1
        core = Core(session_id=session_id)
        core.start_background_tick()
        with self._lock:
            self.sessions[session_id] = {
                "core": core,
                "label": label,
                "user_id": user_id
            }
            if user_id:
                self.active_sessions[user_id] = session_id

        print(f"[SessionManager] Created session {session_id}")
        return session_id

    def get_session(self, session_id=None, user_id=None):
        with self._lock:
            if session_id is None and user_id:
                session_id = self.active_sessions.get(user_id)
            return self.sessions.get(session_id, {}).get("core")

    def get_session_record(self, session_id):
        with self._lock:
            session = self.sessions.get(session_id)
            return dict(session) if session else None


    def get_all_sessions(self):
        with self._lock:
            sessions_snapshot = list(self.sessions.items())
        return [
            {
                "id": sid,
                "label": s["label"],
                "user_id": s.get("user_id")
            }
            for sid, s in sessions_snapshot
        ]


    def delete_session(self, session_id):
        with self._lock:
            session = self.sessions.get(session_id)
        if session:
            core = session["core"]
            core.teardown()
            with self._lock:
                self.sessions.pop(session_id, None)
            print(f"[SessionManager] Deleted session {session_id}")
            with self._lock:
                if session_id == self.active_session_id:
                    self.active_session_id = next(iter(self.sessions), None)
            return True
        return False

    def set_active_session(self, session_id, user_id):
        with self._lock:
            if session_id in self.sessions and self.get_session_user_id(session_id) == user_id:
                self.active_sessions[user_id] = session_id
                print(f"[SessionManager] Switched {user_id} to session {session_id}")
                return True
            return False


    def get_user_sessions(self, user_id):
        with self._lock:
            sessions_snapshot = list(self.sessions.items())
        return [
            {"id": sid, "label": s["label"], "user_id": s.get("user_id")}
            for sid, s in sessions_snapshot
            if s.get("user_id") == user_id
        ]

    def get_session_user_id(self, session_id):
        with self._lock:
            return self.sessions.get(session_id, {}).get("user_id")

    def should_cleanup(self, core):
        MAX_SESSION_AGE = 3600  # seconds (30 minutes)
        start = getattr(core, "start_time", 0)
        age = time.time() - start
        return age > MAX_SESSION_AGE




# Global singleton instance
session_manager = SessionManager()

# Create an initial default session immediately
#session_manager.create_session()
