import json
import os
import glob
from pathlib import Path
from pulse.agents.pulse_gemini import PulseGemini

STATE_DIR = Path("state")
LOG_FILE = STATE_DIR / "pulse_captured_gemini.log"
GEMINI_TMP = Path(os.path.expanduser("~/.gemini/tmp"))
CHATS_DIR = GEMINI_TMP / "pulse" / "chats"

def restore_logs():
    print(f"Restoring logs from {CHATS_DIR}")
    files = glob.glob(str(CHATS_DIR / "*.json"))
    
    # Sort files by creation/modification time to process oldest first
    files.sort(key=os.path.getmtime)
    
    daemon = PulseGemini(verbose=False)
    # Ignore the timestamp block by wiping it out in memory
    daemon.last_timestamp = ""
    daemon.processed_ids = set()
    
    # Pre-load already known timestamps/messages to prevent duplicates
    known_signatures = set()
    if LOG_FILE.exists():
        with open(LOG_FILE, "r", encoding="utf-8") as f:
            for line in f:
                if " | SIG: " in line:
                    sig = line.split(" | SIG: ")[1].strip()
                    known_signatures.add(sig)

    total_added = 0
    with open(LOG_FILE, "a", encoding="utf-8") as out:
        for filepath in files:
            p = Path(filepath)
            # Re-read file parsing
            try:
                with open(p, "r", encoding="utf-8") as f:
                    data = json.load(f)
            except Exception:
                continue
            
            messages = data.get("messages", [])
            for msg in messages:
                role = msg.get("type", "").upper()
                content = msg.get("content", "")
                ts = msg.get("timestamp")
                
                if not content:
                    if msg.get("thoughts"): content = "[Thinking...]"
                    elif msg.get("toolCalls"): content = "[Tool Call]"
                
                if content:
                    log_line = daemon._format_log_entry(ts, role, daemon._clean_text(content))
                    sig = log_line.split(" | SIG: ")[1].strip()
                    
                    if sig not in known_signatures:
                        out.write(log_line + "\n")
                        known_signatures.add(sig)
                        total_added += 1
                        
    print(f"Successfully restored {total_added} missing interactions to {LOG_FILE.name}")

if __name__ == "__main__":
    restore_logs()
