#!/usr/bin/env python3
"""
The definitive multi-mode AI driver for a Roomba. (FINAL "Situational Awareness" Version)
- This version uses a robust, multi-stage AI prompt that gives the robot a
  sense of its physical size and how to navigate cluttered areas.
- It includes a "Post-Bump Recovery" protocol to force re-orientation.
- This is the final, complete, and debugged version of the driver script.
"""
import os, re, json, time, base64, requests
from datetime import datetime
from pydantic import BaseModel, ValidationError
from collections import deque
from typing import Any, List

# --- CONFIGURATION (Final Version) ---
CFG = {
    "CTRL_URL": "http://192.168.5.15:5000",
    "LLM_URL": "http://127.0.0.1:1234/v1/chat/completions",
    "MODEL": "google/gemma-3-4b",
    "API_TOUT": 30,
    "LLM_TOUT": 90,
    "PAUSE": 0.25,
    "FRAME_DIR": "frames",
    "BAT_MIN": 20.0,
    "HISTORY_LEN": 4,
    "ULTRASONIC_CRITICAL_CM": 25.0,  # The AI's immediate danger zone
    "ULTRASONIC_CAUTIOUS_CM": 50.0   # The AI's "cluttered area" zone
}
os.makedirs(CFG["FRAME_DIR"], exist_ok=True)

class RoombaCmd(BaseModel):
    maneuver: str
    duration: float
    scene: Any
    reasoning: str

def _post(endpoint, payload=None, timeout=None):
    url = f"{CFG['CTRL_URL']}/{endpoint}"
    r = requests.post(url, json=payload, timeout=timeout or CFG["API_TOUT"])
    r.raise_for_status()
    return r.json()

def _get(endpoint):
    url = f"{CFG['CTRL_URL']}/{endpoint}"
    r = requests.get(url, timeout=CFG["API_TOUT"])
    r.raise_for_status()
    return r.json()

def save_frame(b64_data):
    fn = datetime.now().strftime("%Y%m%d_%H%M%S") + ".jpg"
    open(os.path.join(CFG["FRAME_DIR"], fn), "wb").write(base64.b64decode(b64_data))
    print(f"📸 Saved frame {fn}")

# --- CORE AI LOGIC (FINAL "SITUATIONAL AWARENESS" PROMPT) ---
def get_ai_command(img_b64, status, history, distance_cm) -> RoombaCmd:
    # This is the final, most advanced system prompt.
    sys_prompt = (
        "You are a precise, logical robot control system. Your mission is to explore and clean. You are controlling a wide, circular robot, so you must be cautious near objects even if they are not directly in front of you. "
        "Produce *only* this JSON object:\n"
        "{\n"
        "  \"maneuver\": \"...\",   // one of: forward, left, right\n"
        "  \"duration\": ...,       // seconds, float (0.5 to 1.0)\n"
        "  \"scene\": \"...\",      // describe what you see\n"
        "  \"reasoning\": \"...\"   // your reason for the chosen maneuver\n"
        "}\n\n"
        "**HIERARCHY OF RULES (obey in strict order of priority):**\n\n"
        "1. **POST-BUMP RECOVERY (Highest Priority):** If the 'Previous Actions' list contains `BUMP_ESCAPE` or `HW_ESCAPE`, your position is uncertain. You **MUST** make a 'left' or 'right' turn for 0.8 seconds to re-orient and scan your new surroundings, regardless of any other rule.\n\n"
        f"2. **IMMEDIATE DANGER (Sensor):** If the Ultrasonic Distance is **LESS THAN {CFG['ULTRASONIC_CRITICAL_CM']} cm**, an impact is imminent. You **MUST** turn 'left' or 'right' for 0.6 seconds to avoid the collision.\n\n"
        "3. **VISUAL THREAT (Camera):** If Rule #1 and #2 do not apply, analyze the camera. If the camera clearly shows a large, solid, impassable obstacle directly ahead (a **closed door, a wall, furniture legs**), you **MUST** turn 'left' or 'right' for 0.6 seconds to find a clear path.\n\n"
        f"4. **CAUTIOUS MANEUVERING (Cluttered Zone):** If the Ultrasonic Distance is **BETWEEN {CFG['ULTRASONIC_CRITICAL_CM']} cm AND {CFG['ULTRASONIC_CAUTIOUS_CM']} cm**, you are in a cluttered area. Do not move forward. Your goal is to find more space. You **MUST** turn 'left' or 'right' for 0.6 seconds to point towards a more open area visible in the camera.\n\n"
        f"5. **EXPLORE (Clear Path):** If the Ultrasonic Distance is **GREATER THAN {CFG['ULTRASONIC_CAUTIOUS_CM']} cm** and no other rules apply, the path is wide open. You **MUST** move 'forward' for 1.0 second.\n"
    )

    # *** THIS IS THE LOGIC BLOCK THAT WAS MISSING ***
    history_str = ", ".join(history) if history else "None"
    user_text = f"Current Status: {status['battery_percent']:.1f}% battery. Ultrasonic Distance: {distance_cm:.1f} cm. Previous Actions: [{history_str}]."
    messages = [{"role": "system", "content": sys_prompt}, {"role": "user", "content": [{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"}}, {"type": "text", "text": user_text}]}]
    
    try:
        resp = requests.post(CFG["LLM_URL"], json={"model": CFG["MODEL"], "messages": messages, "temperature": 0.0, "max_tokens": 300}, timeout=CFG["LLM_TOUT"])
        resp.raise_for_status()
        raw_text = resp.json()["choices"][0]["message"]["content"]
        json_match = re.search(r"\{.*\}", raw_text, re.S)
        if not json_match:
            raise ValueError("No JSON object found in AI response")
        obj = json.loads(json_match.group(0))
        return RoombaCmd(**obj)
    except Exception as e:
        return RoombaCmd(maneuver="left", duration=0.5, scene="AI_FALLBACK", reasoning=f"Error: {e}")

# --- MISSION AND MENU LOGIC ---
def run_mission(is_cleaning: bool):
    mode = "CLEANING" if is_cleaning else "EXPLORATION"
    print(f"\n🚀 Starting {mode} mission... Press Ctrl+C to stop.")
    action_history = deque(maxlen=CFG["HISTORY_LEN"])
    has_undocked = False
    
    try:
        if is_cleaning:
            print("🧹 Starting vacuum motors...")
            _post("vacuum", {"on": True})
            
        while True:
            status = _get("status")
            if not has_undocked and status.get("docked"):
                print("⚓ Robot is docked. Executing undock maneuver...")
                _post("undock")
                has_undocked = True
                action_history.append("undock")
                time.sleep(3.0)
                continue
            
            if status.get("battery_percent", 100) < CFG["BAT_MIN"]:
                print("⚡ Battery low! Ending mission.")
                break
            
            try:
                dist_data = _get("get_ultrasonic_distance")
                distance_cm = dist_data.get("distance_cm", 999.0)
                if distance_cm < 10.0:
                    print(f"⚠️ HARDWARE OVERRIDE! Object at {distance_cm:.1f} cm. Escaping.")
                    _post("move", {"maneuver": "backward", "duration": 0.8})
                    _post("move", {"maneuver": "left", "duration": 0.8})
                    action_history.append("HW_ESCAPE")
                    time.sleep(CFG["PAUSE"])
                    continue
                
                bumper_status = _get("bumper")
                if bumper_status.get("bumped"):
                    print("🚨 PHYSICAL BUMP! Overriding AI to escape.")
                    _post("move", {"maneuver": "backward", "duration": 1.0})
                    _post("move", {"maneuver": "left", "duration": 0.8})
                    action_history.append("BUMP_ESCAPE")
                    time.sleep(CFG["PAUSE"])
                    continue
            except Exception as e:
                print(f"⚠️ Could not get sensor status: {e}")
                distance_cm = 999.0
            
            img_b64 = _get("image").get("image_base64", "")
            if not img_b64:
                cmd = RoombaCmd(maneuver="left", duration=0.5, scene="NO_IMAGE", reasoning="No image received from server")
            else:
                save_frame(img_b64)
                cmd = get_ai_command(img_b64, status, list(action_history), distance_cm)
            
            print(f"\n🔋 {status.get('battery_percent', 0):.1f}% | 📏 {distance_cm:.1f} cm | History: {list(action_history)}")
            print(f"🤔 AI Reasoning: {cmd.reasoning}")
            print(f"↳ Executing: {cmd.maneuver:<8} for {cmd.duration:.2f}s. (Scene: {cmd.scene})")
            
            _post("move", {"maneuver": cmd.maneuver, "duration": cmd.duration}, timeout=cmd.duration + 10)
            action_history.append(cmd.maneuver)
            time.sleep(CFG["PAUSE"])
            
    except KeyboardInterrupt:
        print("\n🛑 User interrupted mission.")
    except Exception as e:
        print(f"❌ Unrecoverable mission error: {e}")
    finally:
        print("--- Mission Ending ---")
        if is_cleaning:
            print("🧹 Stopping vacuum motors...")
            try:
                _post("vacuum", {"on": False})
            except Exception as e:
                print(f"Could not stop vacuum: {e}")
        try:
            _post("move", {"maneuver": "stop", "duration": 0})
        except Exception as e:
            print(f"Could not send stop command: {e}")
        print("Mission complete.")

def main_menu():
    while True:
        print("\n" + "="*50)
        print("  ROOMBA AI CONTROL (AWARENESS V5)")
        print("="*50)
        try:
            status = _get("status")
            print(f"Status: 🔋 {status.get('battery_percent', 'N/A')}% | ⚓ Docked: {status.get('docked', 'N/A')}")
        except Exception as e:
            print(f"Status: ⚠️ Could not connect to control server: {e}")
            time.sleep(3)
            continue
        
        print("\nCHOOSE MISSION:\n  1. Explore (No Vacuum)\n  2. Clean   (With Vacuum)\n  q. Quit")
        choice = input("Enter your choice: ").lower().strip()
        
        if choice == '1':
            run_mission(is_cleaning=False)
        elif choice == '2':
            run_mission(is_cleaning=True)
        elif choice == 'q':
            print("Exiting program.")
            break
        else:
            print("Invalid choice.")
        time.sleep(1)

if __name__ == "__main__":
    try:
        main_menu()
    except KeyboardInterrupt:
        print("\nExiting program.")
