import sys, sqlite3, tempfile
from pathlib import Path
from unittest.mock import patch
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
_DB = Path(tempfile.mktemp(suffix=".db"))

def _mk():
    c = sqlite3.connect(str(_DB)); c.row_factory = sqlite3.Row
    c.execute("PRAGMA journal_mode=WAL")
    for s in ["CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, agent TEXT NOT NULL, started_at TEXT NOT NULL, ended_at TEXT, turn_count INTEGER DEFAULT 0, summary TEXT DEFAULT '', user_intent TEXT DEFAULT '', key_decisions TEXT DEFAULT '[]', key_discoveries TEXT DEFAULT '[]', files_touched TEXT DEFAULT '[]', predecessor_session TEXT, domain TEXT DEFAULT 'general', status TEXT DEFAULT 'active', metadata TEXT DEFAULT '{}')",
           "CREATE INDEX IF NOT EXISTS idx_sa ON sessions(agent, started_at DESC)",
           "CREATE INDEX IF NOT EXISTS idx_ss ON sessions(status)",
           "CREATE TABLE IF NOT EXISTS session_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, role TEXT NOT NULL, content TEXT NOT NULL, content_len INTEGER DEFAULT 0, timestamp TEXT NOT NULL, domain TEXT DEFAULT 'general', metadata TEXT DEFAULT '{}')",
           "CREATE INDEX IF NOT EXISTS idx_ts ON session_turns(session_id, turn_index)"]:
        c.execute(s)
    c.commit(); return c

def _gc():
    c = sqlite3.connect(str(_DB), check_same_thread=False)
    c.row_factory = sqlite3.Row; c.execute("PRAGMA journal_mode=WAL"); return c

def t1():
    print("lifecycle...", end=" "); _mk()
    with patch("pulse.core.brain_db.get_conn", _gc):
        from pulse.brain.session.session_lifecycle import start_session, record_turn, end_session, get_recent_sessions, get_active_session, get_session_turns
        sid = start_session("claude"); assert sid.startswith("ses_claude_")
        assert get_active_session("claude") == sid
        record_turn(sid, "user", "Fix memory"); record_turn(sid, "agent", "Done")
        assert len(get_session_turns(sid)) == 2
        end_session(sid, summary="Fixed", user_intent="Memory fix")
        s = get_recent_sessions(5); assert s[0]["status"] == "completed"
        assert s[0]["turn_count"] == 2
    print("PASS")

def t2():
    print("cross-agent...", end=" "); _mk()
    with patch("pulse.core.brain_db.get_conn", _gc):
        from pulse.brain.session.session_lifecycle import start_session, end_session, get_recent_sessions
        end_session(start_session("claude"), summary="C"); end_session(start_session("gemini"), summary="G")
        assert {s["agent"] for s in get_recent_sessions(5)} == {"claude", "gemini"}
    print("PASS")

def t3():
    print("orphan...", end=" "); _mk()
    with patch("pulse.core.brain_db.get_conn", _gc):
        from pulse.brain.session.session_lifecycle import start_session, get_recent_sessions
        import time as _t
        s1 = start_session("claude"); _t.sleep(1.1); start_session("claude")
        assert any(s["id"]==s1 and s["status"]=="abandoned" for s in get_recent_sessions(5))
    print("PASS")

def t4():
    print("boot ctx...", end=" "); _mk()
    with patch("pulse.core.brain_db.get_conn", _gc):
        from pulse.brain.session.session_lifecycle import start_session, end_session
        from pulse.brain.session.session_context import build_recent_sessions_context
        end_session(start_session("claude"), user_intent="Cross-session memory")
        ctx = build_recent_sessions_context(3)
        assert "RECENT SESSIONS" in ctx and "claude" in ctx
    print("PASS")

def t5():
    print("code checks...", end=" ")
    assert "_CONVERSATIONAL_WEIGHT = 0.85" in (ROOT/"pulse/brain/search_sources_episodic.py").read_text()
    assert "d = min(_days / 7.0, 1.0)" in (ROOT/"pulse/brain/brain_search/search_scoring.py").read_text()
    assert "_is_recent" in (ROOT/"pulse/brain/brain_search/search_scoring.py").read_text()
    assert '"episodic", "working_memory"' in (ROOT/"pulse/brain/brain_search/search_engine.py").read_text()
    assert "build_recent_sessions_context" in (ROOT/"pulse/brain/pulse_boot.py").read_text()
    assert "CREATE TABLE IF NOT EXISTS sessions" in (ROOT/"pulse/core/brain_db.py").read_text()
    print("PASS")

if __name__ == "__main__":
    p=f=0
    for fn in [t1,t2,t3,t4,t5]:
        try: fn(); p+=1
        except Exception as e: f+=1; print(f"FAIL: {e}")
    try: _DB.unlink(missing_ok=True)
    except: pass
    print(f"Results: {p}/{p+f} passed")
    sys.exit(0 if f==0 else 1)