#!/usr/bin/env python3
"""
Voice-to-Task Bridge
Watches VOICE_INPUT.txt and adds tasks to AIVA queue.

Workflow:
1. User speaks into Wispr Flow → text in VOICE_INPUT.txt
2. This script detects change
3. Parses voice command
4. Adds to Redis task queue
5. AIVA orchestrator picks up and dispatches
"""

import os
import sys
import re
import time
import json
from pathlib import Path
from datetime import datetime

# Load secrets
secrets_path = Path("/mnt/e/genesis-system/config/secrets.env")
if secrets_path.exists():
    with open(secrets_path) as f:
        for line in f:
            if "=" in line and not line.startswith("#"):
                key, value = line.strip().split("=", 1)
                os.environ[key] = value.strip('"')

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import redis

# Paths
VOICE_INPUT = Path("/mnt/e/genesis-system/VOICE_INPUT.txt")
MISSION_OUTPUT = Path("/mnt/e/genesis-system/templates/current_mission.md")

# Redis
REDIS_CONFIG = {
    "host": os.environ.get("GENESIS_REDIS_HOST", "redis-genesis-u50607.vm.elestio.app"),
    "port": int(os.environ.get("GENESIS_REDIS_PORT", 26379)),
    "password": os.environ.get("GENESIS_REDIS_PASSWORD", ""),
    "decode_responses": True,
}
QUEUE_KEY = "genesis:task_queue"


def parse_voice(text: str) -> dict:
    """Parse voice input into task fields."""
    result = {
        "title": "",
        "description": text.strip(),
        "priority": 3,
        "max_iterations": 30,
        "auto_start": text.lower().strip().endswith(("go", "go.", "execute", "start")),
    }

    # Extract project name as title
    match = re.search(r"(?:new\s+)?project[:\s]+([a-zA-Z0-9_\s-]+?)(?:\.|objective|goal|$)", text, re.I)
    if match:
        result["title"] = match.group(1).strip().replace(" ", "-")

    # Extract priority
    if any(w in text.lower() for w in ["urgent", "critical", "asap", "immediately"]):
        result["priority"] = 1
    elif any(w in text.lower() for w in ["important", "high priority"]):
        result["priority"] = 2
    elif any(w in text.lower() for w in ["low priority", "when you can", "background"]):
        result["priority"] = 5

    # Extract max iterations
    match = re.search(r"max\s+(\d+)", text, re.I)
    if match:
        result["max_iterations"] = int(match.group(1))

    # Use first sentence as title if not found
    if not result["title"]:
        first_sentence = text.split(".")[0][:50]
        result["title"] = first_sentence.strip()

    return result


def add_to_queue(parsed: dict) -> str:
    """Add task to Redis queue."""
    import hashlib

    r = redis.Redis(**REDIS_CONFIG)

    task_id = hashlib.md5(f"{parsed['title']}{time.time()}".encode()).hexdigest()[:12]

    task = {
        "id": task_id,
        "title": parsed["title"],
        "description": parsed["description"],
        "priority": parsed["priority"],
        "status": "pending",
        "created_at": datetime.now().isoformat(),
        "max_iterations": parsed["max_iterations"],
        "source": "voice",
    }

    score = parsed["priority"] * 1000000 + time.time()
    r.zadd(QUEUE_KEY, {json.dumps(task): score})

    return task_id


class VoiceHandler(FileSystemEventHandler):
    """Handle voice input file changes."""

    def __init__(self):
        self.last_content = ""
        self.last_time = 0

    def on_modified(self, event):
        if not event.src_path.endswith("VOICE_INPUT.txt"):
            return

        # Debounce
        if time.time() - self.last_time < 2:
            return

        try:
            time.sleep(0.5)  # Wait for file write
            content = VOICE_INPUT.read_text().strip()

            # Skip if unchanged or just comments
            lines = [l for l in content.split("\n") if l.strip() and not l.strip().startswith("#")]
            text = "\n".join(lines)

            if not text or text == self.last_content:
                return

            self.last_content = text
            self.last_time = time.time()

            print(f"\n{'='*50}")
            print(f"🎤 Voice input detected!")
            print(f"{'='*50}")
            print(f"Input: {text[:100]}...")

            # Parse
            parsed = parse_voice(text)
            print(f"\n📋 Parsed:")
            print(f"   Title: {parsed['title']}")
            print(f"   Priority: {parsed['priority']}")
            print(f"   Auto-start: {parsed['auto_start']}")

            # Add to queue
            task_id = add_to_queue(parsed)
            print(f"\n✅ Added to AIVA queue: {task_id}")

            # Generate mission file
            mission = f"""# MISSION: {parsed['title'].upper()}

**Added**: {datetime.now().isoformat()}
**Task ID**: {task_id}
**Priority**: {parsed['priority']}

## Description
{parsed['description']}

## Status
Queued for AIVA orchestrator
"""
            MISSION_OUTPUT.write_text(mission)
            print(f"📄 Mission file: {MISSION_OUTPUT}")

            print(f"\n{'='*50}\n")

        except Exception as e:
            print(f"Error: {e}")


def main():
    print("""
╔════════════════════════════════════════════════════════╗
║           VOICE-TO-TASK BRIDGE                         ║
║                                                        ║
║  Watching: E:\\genesis-system\\VOICE_INPUT.txt          ║
║  Queue:    Redis → AIVA Orchestrator                   ║
║                                                        ║
║  Speak with Wispr Flow → Save file → Task queued       ║
╚════════════════════════════════════════════════════════╝
""")

    # Create input file if missing
    if not VOICE_INPUT.exists():
        VOICE_INPUT.write_text("# Speak your command here with Wispr Flow\n# Save file to queue task\n\n")

    observer = Observer()
    observer.schedule(VoiceHandler(), str(VOICE_INPUT.parent), recursive=False)
    observer.start()

    print("👂 Listening...\n")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        print("\n👋 Stopped")

    observer.join()


if __name__ == "__main__":
    main()
