import logging
import json
import os
import re
from genesis_v2.core.jules_bridge import JulesBridge

logger = logging.getLogger(__name__)

INSIGHTS_DIR = "e:/genesis-system/hive/strategic_insights"

def parse_sessions(output: str):
    """Parses the remote list tabular output."""
    sessions = []
    # Split by actual newlines to account for Windows \r\n
    lines = output.splitlines()
    for line in lines:
        if 'ID' in line or '---' in line or not line.strip():
            continue
        parts = re.split(r'\s{2,}', line.strip())
        if len(parts) >= 4:
            sessions.append({
                "id": parts[0],
                "description": parts[1],
                "repo": parts[2],
                "status": parts[-1]
            })
    return sessions

def fetch_completed_insights():
    """Polls Jules for completed sessions and saves their insights."""
    logging.basicConfig(level=logging.INFO)
    logger.info("Polling Jules for completed strategic sessions...")
    
    bridge = JulesBridge()
    output = bridge.list_sessions()
    
    if not output:
        logger.warning("No output from Jules session list.")
        return

    os.makedirs(INSIGHTS_DIR, exist_ok=True)
    sessions = parse_sessions(output)
    logger.info(f"Parsed sessions: {sessions}")
    
    for session in sessions:
        if "Completed" in session["status"]:
            session_id = session["id"]
            insight_file = os.path.join(INSIGHTS_DIR, f"jules_insight_{session_id}.md")
            
            if not os.path.exists(insight_file):
                logger.info(f"Found new completed session: {session_id}. Pulling insights...")
                # We do not apply patch automatically for strategic insights by default, 
                # we just want to read the analysis.
                patch_data = bridge.pull_session(session_id, apply_patch=False)
                
                with open(insight_file, "w", encoding="utf-8") as f:
                    # Storing raw patch output which usually contains the AI's response/thought process.
                    f.write(f"# Jules Strategic Insight - Session {session_id}\n\n")
                    f.write(f"**Description**: {session['description']}\n\n")
                    f.write(f"```diff\n{patch_data}\n```\n")
                    
                logger.info(f"Insight saved to {insight_file}")
            else:
                logger.debug(f"Session {session_id} already processed.")

if __name__ == "__main__":
    fetch_completed_insights()
