#!/usr/bin/env python3
"""
Genesis Auto-Pilot — Recursive System Developer
================================================
Monitors the WORK_QUEUE_TODAY.md and executes missions autonomously.
Uses the Bipartite Model:
- Antigravity: Execution & Orchestration
- Jules: Strategy, Research & Creative

Usage:
  python3 scripts/genesis_autopilot.py --loop
"""

import asyncio
import json
import logging
import os
import sys
import time
from pathlib import Path
from datetime import datetime
from dataclasses import asdict

# Path setup
GENESIS_ROOT = Path("/mnt/e/genesis-system")
sys.path.insert(0, str(GENESIS_ROOT))

from core.antigravity_workflow import AntigravityWorkflow
from core.jules_bridge import JulesArchitect

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(GENESIS_ROOT / "data" / "logs" / "autopilot.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("genesis.autopilot")

QUEUE_FILE = GENESIS_ROOT / ".gemini" / "knowledge" / "WORK_QUEUE_TODAY.md"

class GenesisAutopilot:
    def __init__(self):
        self.workflow = AntigravityWorkflow()
        self.jules = JulesArchitect()
        self.active = False

    def _read_queue(self) -> str:
        if not QUEUE_FILE.exists():
            return ""
        return QUEUE_FILE.read_text()

    def _update_queue(self, content: str):
        QUEUE_FILE.write_text(content)

    async def run_cycle(self):
        """Perform one iteration of the development loop."""
        logger.info("Starting Auto-Pilot Cycle...")
        
        queue_content = self._read_queue()
        if not queue_content:
            logger.warning("Queue file empty or not found.")
            return

        # Simple extraction of the current P0/P1 goal using Antigravity's executor
        # We ask Gemini to identify the next incomplete task from the markdown
        extract_prompt = f"""Review this Work Queue and identify the NEXT incomplete P0 or P1 task.
Return ONLY the task description. If all are done, return "ALL_DONE".

QUEUE:
{queue_content}
"""
        task_resp = self.workflow.executor.execute_optimized(extract_prompt, task_type="summarization")
        task_goal = task_resp.response.strip()

        if "ALL_DONE" in task_goal:
            logger.info("All tasks in queue completed. Resting.")
            return

        logger.info(f"Identified Priority Task: {task_goal}")

        # 1. Strategy Choice: Does this need Jules?
        # If it's marketing, research, or compliance, delegate to Jules.
        needs_jules = any(keyword in task_goal.lower() for keyword in ["outreach", "strategy", "compliance", "research", "draft"])
        
        if needs_jules:
            logger.info("Delegating to Jules (Strategic/Creative)...")
            # We'll use Jules to draft a strategy/content
            jules_resp = await self.jules._delegate_to_jules(f"Plan and draft the output for this task: {task_goal}", "auto_delegation")
            
            if jules_resp.get("success"):
                logger.info("Jules task completed successfully.")
                # Feed Jules' output into Antigravity for implementation if needed
                implementation_goal = f"Implement the strategy drafted by Jules for: {task_goal}. Jules output: {jules_resp.get('result')[:500]}..."
                plan = self.workflow.create_plan(implementation_goal)
                self.workflow.execute_plan(asdict(plan))
            else:
                logger.error(f"Jules delegation failed: {jules_resp.get('error')}")
        else:
            # Direct Antigravity implementation
            logger.info("Executing via Antigravity (Direct Implementation)...")
            plan = self.workflow.create_plan(task_goal)
            self.workflow.execute_plan(asdict(plan))

        # 2. Update Queue
        # Mark task as [DONE] in the file
        logger.info("Updating Work Queue status...")
        updated_queue = queue_content.replace(task_goal, f"~~{task_goal}~~ [COMPLETED BY AUTO-PILOT {datetime.now().strftime('%Y-%m-%d %H:%M')}]")
        self._update_queue(updated_queue)
        
        logger.info("Cycle complete.")

    async def start(self, loop=True):
        self.active = True
        logger.info("Genesis Auto-Pilot System ONLINE.")
        
        while self.active:
            try:
                await self.run_cycle()
            except Exception as e:
                logger.error(f"Error in cycle: {e}")
            
            if not loop:
                break
                
            logger.info("Sleeping for 10 minutes before next cycle...")
            await asyncio.sleep(600)  # Wait 10 mins

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--loop", action="store_true", help="Run in a continuous loop")
    args = parser.parse_args()

    autopilot = GenesisAutopilot()
    asyncio.run(autopilot.start(loop=args.loop))
